1

I have a string like "2020-01-20T11:00:05-05:00", and I want to compare this with datetime.now() to see if it is greater than it.

I think I need to use datetime.strptime(..., ...) although I don't know what to do about the timezone bit.

How can I solve this?

Thanks.

EDIT: date_time = datetime.strptime("2020-01-20T11:00:05-05:00", "%Y-%m-%dT%H:%M:%S%z"). This works, however now when I compare them I get TypeError: can't compare offset-naive and offset-aware datetimes.

EDIT2: Perhaps I need to make my datetime.now() timezone aware?

Jason Whitman
  • 73
  • 3
  • 8

1 Answers1

0

As I stated, it seems that link provides the information you need for the question. However I will add a full working example. Using pytz and datetime:

import pytz
from datetime import datetime

now = datetime.now(pytz.utc)
if now < datetime.strptime("2020-01-21T11:00:05-05:00", "%Y-%m-%dT%H:%M:%S%z"):
    print("A")
else:
    print("B")

Output:

B

Changing the day to "10" to make sure the statime is True:

if now < datetime.strptime("2020-01-10T11:00:05-05:00", "%Y-%m-%dT%H:%M:%S%z"):
    print("A")
else:
    print("B")

Output:

A

Another option as Jason Whitman mentioned using datetime.timezone.utc changing the imports and using it will work:

from datetime import datetime, timezone

now = datetime.now(timezone.utc)
if now < datetime.strptime("2020-01-21T11:00:05-05:00", "%Y-%m-%dT%H:%M:%S%z"):
    print("A")
else:
    print("B")
Celius Stingher
  • 17,835
  • 6
  • 23
  • 53