Python Forum
Convert UTC now() to local time to compare to a strptime()
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Convert UTC now() to local time to compare to a strptime()
#1
Question 
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?
Reply
#2
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.
Reply
#3
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  String formatting (strptime) issues Henrio 2 897 Jan-06-2023, 06:57 PM
Last Post: deanhystad
  How to change UTC time to local time in Python DataFrame? SamKnight 2 1,670 Jul-28-2022, 08:23 AM
Last Post: Pedroski55
  Convert looping home security to a one time scan of switches and sensors duckredbeard 0 1,794 Dec-08-2020, 04:31 AM
Last Post: duckredbeard
  Convert to UTC without changing time pythonlearner1 1 2,159 Nov-05-2020, 09:54 PM
Last Post: pythonlearner1
  Extracting year from a string using strptime and datetime builtin Drone4four 3 8,848 Aug-11-2020, 12:02 PM
Last Post: ndc85430
  Convert quarterly time series to monthly time series donnertrud 1 5,241 May-22-2020, 10:16 AM
Last Post: pyzyx3qwerty
  Convert weekly sequences to date and time. SinPy 0 1,486 Nov-23-2019, 05:20 PM
Last Post: SinPy
  Parse Binary Data File and convert Epoch Time drdevereaux 1 3,245 May-16-2019, 01:56 AM
Last Post: Larz60+
  Convert Column To Time Talch 1 2,713 Aug-16-2018, 03:02 PM
Last Post: mlieqo
  Convert from datetime to time.struct_time object chris0147 0 4,422 Mar-11-2018, 12:01 AM
Last Post: chris0147

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020