0

I have a string, there is a time in it. It looks like 2023-04-23T19:01:00-04:00.

I want to get the date from this line and compare it with today's. I have a problem with it because, it has -04:00 in the end, and I don't know how to place it to datetime.strptime.

I'd like to use datetime.

(I think that -04:00 is UTC-4, I don't know how to use it.)

mkrieger1
  • 19,194
  • 5
  • 54
  • 65

2 Answers2

1

datetime.fromisoformat seems to be what you are looking for.

>>> from datetime import datetime
>>> dt = datetime.fromisoformat('2023-04-23T19:01:00-04:00')
>>> print(dt)
2023-04-23 19:01:00-04:00
>>> print(dt.year)
2023
>>> print(dt.tzinfo)
UTC-04:00
0

You can use the datetime module in Python to parse the string and compare it with the current date. The -04:00 at the end of the string is indeed the timezone offset (UTC-4). You can use the pytz library to handle the timezone:

from datetime import datetime
import pytz

time_str = "2023-04-23T19:01:00-04:00"
dt = datetime.strptime(time_str, "%Y-%m-%dT%H:%M:%S%z")
now = datetime.now(pytz.UTC)


dt = dt.astimezone(now.tzinfo)


if dt.date() == now.date():
    print("The dates are the same.")
else:
    print("The dates are different.")
Matteo Buffagni
  • 312
  • 2
  • 10