Python – Specify datetime timezone using pytz

We can use the dateutil package to create timezone aware datetime.

 

We can also use the pytz to specify the timezone. Try the following example.

import pytz
import datetime

local_tz = pytz.timezone ("Asia/Hong_Kong")
datetime_without_tz = datetime.datetime.strptime("2015-02-14 12:34:56", "%Y-%m-%d %H:%M:%S")
datetime_with_tz = local_tz.localize(datetime_without_tz, is_dst=None) # No daylight saving time

str1 = datetime_without_tz.strftime('%Y-%m-%d %H:%M:%S %Z')
str2 = datetime_with_tz.strftime('%Y-%m-%d %H:%M:%S %Z')

print 'Without Timzone : %s' % (str1)
print 'With Timezone   : %s' % (str2)


python-timezone-aware-datetime-using-pytz
 

Done =)

Reference: StackOverflow – How do I convert local time to UTC in Python?

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.