10

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.

FObersteiner
  • 22,500
  • 8
  • 42
  • 72
Flying Thunder
  • 890
  • 2
  • 11
  • 37
  • 1
    You need to change the data type since comparison is not defined for str vs datetime types. Another option you have is to convert datetime into str by `str` function, which is applied under the hood when you print them. – Kota Mori May 20 '20 at 12:58
  • Does this answer your question? [Converting string into datetime](https://stackoverflow.com/questions/466345/converting-string-into-datetime) – Panagiotis Simakis May 20 '20 at 13:04
  • no, the accepted answer to this question is exactly what i did not want to do, and the second best answer requires a third party module, i already got a better answer here – Flying Thunder May 20 '20 at 13:08

2 Answers2

8

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.

FObersteiner
  • 22,500
  • 8
  • 42
  • 72
7

You can use parser provided by dateutil

from dateutil import parser

date_object = parser.parse("2020-05-20 13:01:30")

print(repr(date_object))
# datetime.datetime(2020, 5, 20, 13, 1, 30)

print(type(date_object)) 
# <class 'datetime.datetime'>

print(date_object)  
# 2020-05-20 13:01:30

From the docs:

This module offers a generic date/time string parser which is able to parse most known formats to represent a date and/or time.

Documentation: https://dateutil.readthedocs.io/en/stable/parser.html

Swetank Poddar
  • 1,257
  • 9
  • 23
  • 2
    works too, but since datetime already does the job ill rather use that instead of having to import a module just for this, but thanks! – Flying Thunder May 20 '20 at 13:06
  • Yeah makes sense, but this parser supports many other formats. So you are not restricted with just the ISO format. – Swetank Poddar May 20 '20 at 13:08
  • for ISO format, you probably want to use [isoparse](https://dateutil.readthedocs.io/en/stable/parser.html#dateutil.parser.isoparse) since more efficient than the standard parser. – FObersteiner Jul 05 '22 at 04:46