Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you convert local time (PDT) to PST using python

Usually what I do if I want to convert time zone is the following

# local interpreted as pst to utc

utc = pytz.utc
pst = pytz.timezone('America/Los_Angeles')


start_time_str = time.strftime('%Y-%m-%d %H:%M:%S', \
  time.localtime(start_time))
start_time_datetime = \
  datetime.datetime.strptime(start_time_str, "%Y-%m-%d %H:%M:%S")

start_time_datetime = \
  start_time_datetime.replace(tzinfo=pst).astimezone(utc)

Now I want to do similar stuff such that I want localtime convert to pst

localtime = datetime.datetime.fromtimestamp(time.mktime(
            time.localtime()))

I am not exactly sure how would you achieve this

Any help would be appreciated

like image 816
Kevin Avatar asked Sep 07 '26 04:09

Kevin


1 Answers

Two things:

  1. The "America/Los_Angeles" identifier represents the entire Pacific time zone, including both PST and PDT. It will use the either -8 or -7 as the time zone offset depending on the specific date and time it is used on.

  2. Calling replace(tzinfo=...) is a mistake. Use localize instead. See the pytz documentation. This is discussed in the introduction and in the very first example.

like image 171
Matt Johnson-Pint Avatar answered Sep 09 '26 21:09

Matt Johnson-Pint



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!