Reputation: 791
So I'd like to preface this by saying that I do not want to use datetime.strptime()
, I've written a very simple parser and the code is as follows:
def datetime_parse(s):
return datetime.datetime(int(s[0:4]), int(s[5:7]), int(s[8:10]), int(s[11:13]),
int(s[14:16]), int(s[17:19]), int(s[20:26]))
The issue here is that for my microsecond conversion, I have values such as:
2012-09-30 17:00:04.01350000
When reading it in int()
will automatically round down to 0 and as far as I know datetime.datetime()
will only accept int
s. Is there a workaround for this?
Note: in the original question, which has meanwhile been corrected, the last parameter of datetime.datetime()
was int(s[20:27])
.
Upvotes: 0
Views: 3856
Reputation: 48720
It is working as expected - once you parse back to a string you get the same string going in.
>>> s = '2012-09-30 17:00:04.013500'
>>> d = datetime.datetime(int(s[0:4]), int(s[5:7]), int(s[8:10]), int(s[11:13]), int(s[14:16]), int(s[17:19]), int(s[20:26]))
>>> d.strftime('%Y-%m-%d %H:%M:%S.%f')
'2012-09-30 17:00:04.013500'
Upvotes: 1
Reputation: 1432
The microsecond should be in the range [0, 1E6). You're passing 7 digits instead of 6, so the extra zero is increasing the actual value by a factor of 10. Try int(s[20:26])
instead.
Upvotes: 1