saltycrane / saltycrane-blog-comments

Comments for my blog powered by utterances
https://www.saltycrane.com/blog/
0 stars 0 forks source link

blog/2009/05/converting-time-zones-datetime-objects-python/ #9

Open utterances-bot opened 5 years ago

utterances-bot commented 5 years ago

Converting time zones for datetime objects in Python - SaltyCrane Blog

https://www.saltycrane.com/blog/2009/05/converting-time-zones-datetime-objects-python/

KyferEz commented 5 years ago

How do I set a Non-UTC timezone and then convert to UTC? You don't cover that scenerio... For example, I have the following Date String: "15/Mar/2019:12:00:13" which is in Eastern Time. I want to convert to UTC.

I found out how, it's covered here: http://pytz.sourceforge.net/#localized-times-and-date-arithmetic

Kevin-Prichard commented 5 years ago

datetime.astimezone() is super helpful.

It's sometimes helpful to take a timezone-naive datetime that's sourced and stored as UTC, and transform it to a particular timezone, e.g.

>>> import datetime, pytz
# Timezone-naive datetime, which originally came from a UTC-based system
>>> tz_naive_utc_dt = datetime.datetime(2019, 8, 1, 17, 18)
>>> tz_naive_utc_dt
datetime.datetime(2019, 8, 1, 17, 18)
>>> tz_naive_utc_dt.strftime("%D %T %z")
'08/01/19 17:18:00 '   # Note the trailing space, with no z-offset!

# We replace (add, really) the timezone as UTC, so it's a timezone-aware datetime
>>> tz_aware_utc_dt = tznaive_utc_dt.replace(tzinfo=pytz.timezone('UTC'))
>>> tz_aware_utc_dt
datetime.datetime(2019, 8, 1, 17, 18, tzinfo=<UTC>)
>>> tz_aware_utc_dt.strftime("%D %T %z")
'08/01/19 17:18:00 +0000'  # Note the date and time remain 'unchanged' but now there's a z-offzet

# Finally, push the timezone-aware UTC datetime into another timezone, transforming how it renders
>>> tz_aware_pst_dt = tz_aware_utc_dt.astimezone(pytz.timezone('America/Los_Angeles'))
>>> tz_aware_pst_dt
datetime.datetime(2019, 8, 1, 10, 18, tzinfo=<DstTzInfo 'America/Los_Angeles' PDT-1 day, 17:00:00 DST>)
>>> tz_aware_pst_dt.strftime("%D %T %z")
'08/01/19 10:18:00 -0700'  # Note that the time renders to PST, and the z-offset reflects PST