Python Forum

Full Version: Convert UTC now() to local time to compare to a strptime()
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have a string that contains a local time "2024-12-31 23:59:59". The local time is "America/Edmonton".

The time zone on my machine is UTC, so datetime.now() returns UTC time.

if the current time is less than 30 minutes before the time in my string, I want to generate a time that is 30 minutes from now, in the local time zone. I will be comparing this time to a datetime.strptime() later in my code.

I would normally just use datetime.datetime.now() + datetime.timedelta(minutes=30) but because my system is using UTC time I end up with a UTC time.

How can I convert my offset UTC time to local time so that I can compare it to a datetime.strptime() time?
I think I've come up with an answer:

datetime.datetime.strptime(datetime.datetime.now(pytz.timezone("America/Edmonton")).strftime("%Y-%m-%d %H:%M:%S"), "%Y-%m-%d %H:%M:%S")

Takes the current UTC time, converted to the America/Edmonton timezone. Convert it to a string, then back to a datetime.

I can use the result to compare to the strptime() of my string.
Don't use pytz. Pendulum is a much better time zone library. You can also use the timzone support from the datetime module. Pendulum does not work with 2.7, and datetime added timezone, and I remember you referencing that in other posts.