How do I print a Python datetime in the local timezone?

PythonServer Side ProgrammingProgramming

The easiest way in Python date and time to handle timezones is to use the pytz and tzlocal modules. These libraries allows accurate and cross platform timezone calculations. pytz brings the Olson tz database into Python. It also solves the issue of ambiguous times at the end of daylight saving time, which you can read more about in the Python Library Reference (datetime.tzinfo).

Before you use it you'll need to install it using −

$ pip install pytz tzlocal

Example

You can use the pytz library as follows −

from datetime import datetime
from pytz import timezone
from tzlocal import get_localzone
format = "%Y-%m-%d %H:%M:%S %Z%z"
# Current time in UTC
now_utc = datetime.now(timezone('UTC'))
print(now_utc.strftime(format))
# Convert to local time zone
now_local = now_utc.astimezone(get_localzone())
print(now_local.strftime(format))

Output

This will give the output −

2018-01-03 07:05:50 UTC+0000
2018-01-03 12:35:50 IST+0530
raja
Published on 08-Jan-2018 08:06:33
Advertisements