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?

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s