Python – Create current datetime object with timezone

Handling timezone is quite a pain in Python. When you create or read a datetime object, you need to make sure whether the datetime you need should be timezone aware or not.

Here is a simple example to create a datetime with timezone. The tzlocal will determine the timezone setting of the operating system and apply it to your datetime object.

import datetime
from dateutil.tz import tzlocal
 
now_without_tz = datetime.datetime.now()
now_with_tz    = datetime.datetime.now(tzlocal())

str1 = now_without_tz.strftime('%Y-%m-%d %H:%M:%S %Z')
str2 = now_with_tz.strftime('%Y-%m-%d %H:%M:%S %Z')
 
print 'Without Timzone : %s' % (str1)
print 'With Timezone   : %s' % (str2)

 

Check it out.
python-timezone-aware-datetime
 

Done =)

References:

Advertisements

One thought on “Python – Create current datetime object with timezone”

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