python timezone date

from datetime import datetime
from pytz import timezone

date_str = "2009-05-05 22:28:15"
datetime_obj = datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S")
datetime_obj_utc = datetime_obj.replace(tzinfo=timezone('UTC'))
print datetime_obj_utc.strftime("%Y-%m-%d %H:%M:%S %Z%z")

Show all the US Timezones

There are over 500 Timezones !!

from pytz import all_timezones

print len(all_timezones)
for zone in all_timezones:
    if 'US' in zone:
        print zone

Just find Manila

from pytz import all_timezones

[a for a in all_timezones if a.find('Manila')!=-1]

Convert Timezones

from datetime import datetime
from pytz import timezone

fmt = "%Y-%m-%d %H:%M:%S %Z%z"

# Current time in UTC
now_utc ='UTC'))
print now_utc.strftime(fmt)

# Convert to US/Pacific time zone

now_pacific = now_utc.astimezone(timezone('US/Pacific'))
print now_pacific.strftime(fmt)

# Convert to Europe/Berlin time zone
now_berlin = now_pacific.astimezone(timezone('Europe/Berlin'))
print now_berlin.strftime(fmt)

Convert Manila Time to UTC

Use a time-zone output specifier.

#Get Manila Time - Convert to UTC
fmt = "%Y-%m-%d %H:%M:%S %Z%z"

utc_rise=datetime.strptime(str(sun.rise_time)+" UTC","%Y/%m/%d %H:%M:%S %Z").astimezone(timezone('UTC'))
print("Utc_Rise "+utc_rise.strftime(fmt))
print("PI rise "+pi_rise.strftime(fmt))

Converting an Unknown DateTime string into UTC

I am told this string is UTC ... this is how I convert it, use %Z specifier.


str(sun.rise_time) = '2017/7/18 21:37:08'

utc_rise=datetime.strptime(str(sun.rise_time)+" UTC","%Y/%m/%d %H:%M:%S %Z").astimezone(timezone('UTC')) ```