Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - convert string type to datetime type

I have a two variables that i want to compare. When printed, this is what they look like:

2020-05-20 13:01:30
2020-05-20 14:49:03

However, one is a string type, and the other a datetime type. If I want to convert the string one into date type so I can compare them, is the only way to use strptime? Because this seems a little redundant to me, since the string already has the exact format I want it to have. Basically, is there a function that does the same as strptime, but without re-formating it? As you can imagine, googling this problem is impossible, as all I'm getting is people trying to format any kind of string into datetime, so all the answers are just pointing at strptime.

like image 311
Flying Thunder Avatar asked Mar 08 '26 08:03

Flying Thunder


1 Answers

If you work with Python 3.7+, for ISO 8601 compatible strings, use datetime.fromisoformat() as this is considerably more efficient than strptime or dateutil's parser. Ex:

from datetime import datetime
dtobj = datetime.fromisoformat('2020-05-20 13:01:30')
print(repr(dtobj))
# datetime.datetime(2020, 5, 20, 13, 1, 30)

You can find a benchmark vs. strptime etc. here or here.

like image 153
FObersteiner Avatar answered Mar 11 '26 08:03

FObersteiner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!