Reputation: 23
I want to convert y-m-dTh:m
string formatted datetime
to python datetime
object. I run this code:
>>> import datetime
>>> datetime.datetime.strptime('2020-09-02T22:05', "%Y-%m-%dT%H:%M%f")
My expected output was:
datetime.datetime(2020, 9, 2, 22, 5, 0, 0)
But the real output is showing:
datetime.datetime(2020, 9, 2, 22, 0, 0, 500000)
What's the problem in my code?
Upvotes: 1
Views: 393
Reputation: 25544
If you run Python 3.7 or higher, use fromisoformat
:
from datetime import datetime
datetime.fromisoformat('2020-09-02T22:05')
# datetime.datetime(2020, 9, 2, 22, 5)
Upvotes: 1
Reputation: 13049
The problem is that with the use of %M%f
, it is trying to parse the 05
part as number of minutes followed by number of microseconds.
When used for output (with strftime
), the %M
and various other fields should always produce a 2-digit value, and the %f
should always produce a 6-digit value even if there are leading zeros, so that if you do for example
dt.strftime('%Y-%m-%dT%H:%M:%S.%f')
(where dt
is a datetime object) you might get something like:
2020-01-01T00:00:00.000000
However, on input (with strptime
), it is designed for leniency in handling a string with a one-digit number of minutes and fewer than 6 digits for the microseconds -- and similarly with the other fields. It is probably easiest to see with a decimal point inserted after the seconds in both the string and the format specifier. Both of these:
datetime.datetime.strptime('2020-1-2T3:4:5.6', '%Y-%m-%dT%H:%M:%S.%f')
datetime.datetime.strptime('2020-01-02T03:04:05.600000', '%Y-%m-%dT%H:%M:%S.%f')
give the same output:
datetime.datetime(2020, 1, 2, 3, 4, 5, 600000)
In your case, you do not have any separator such as a decimal point (and in fact, you have both minutes and microseconds but not the seconds, which is probably not useful), but it still tries hard to match the string to the format specifier instead of giving an error. So it identifies the 0
with the minutes and the 5
with the most significant decimal digit of the microseconds -- hence the output that you were seeing.
The solution here is simply to omit the %f
.
>>> datetime.datetime.strptime('2020-09-02T22:05', '%Y-%m-%dT%H:%M')
datetime.datetime(2020, 9, 2, 22, 5)
Upvotes: 0