Python Forum
Convert UTC now() to local time to compare to a strptime() - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Convert UTC now() to local time to compare to a strptime() (/thread-42051.html)



Convert UTC now() to local time to compare to a strptime() - Calab - Apr-29-2024

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?


RE: Convert UTC now() to local time to compare to a strptime() - Calab - Apr-29-2024

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.


RE: Convert UTC now() to local time to compare to a strptime() - deanhystad - Apr-29-2024

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.