Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How do I print a Python datetime in the local timezone?
The easiest way to print a Python datetime in the local timezone is to use the pytz and tzlocal modules. These libraries provide accurate and cross-platform timezone calculations. pytz brings the Olson tz database into Python and solves the issue of ambiguous times at the end of daylight saving time.
Before you use it you'll need to install it using ?
$ pip install pytz tzlocal
Using pytz and tzlocal
You can use the pytz library to convert UTC time to local timezone ?
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))
2018-01-03 07:05:50 UTC+0000 2018-01-03 12:35:50 IST+0530
Using Built-in astimezone() Method
Python 3.6+ provides a simpler approach using the built-in astimezone() method without arguments ?
from datetime import datetime, timezone
# Create UTC datetime
utc_time = datetime.now(timezone.utc)
print("UTC Time:", utc_time.strftime("%Y-%m-%d %H:%M:%S %Z"))
# Convert to local timezone automatically
local_time = utc_time.astimezone()
print("Local Time:", local_time.strftime("%Y-%m-%d %H:%M:%S %Z"))
UTC Time: 2024-01-15 14:30:25 UTC Local Time: 2024-01-15 20:00:25 IST
Getting Current Local Time Directly
To get the current time directly in local timezone ?
from datetime import datetime
# Get current local time
local_now = datetime.now()
print("Current Local Time:", local_now.strftime("%Y-%m-%d %H:%M:%S"))
# Get current local time with timezone info
local_now_tz = datetime.now().astimezone()
print("With Timezone:", local_now_tz.strftime("%Y-%m-%d %H:%M:%S %Z%z"))
Current Local Time: 2024-01-15 20:00:25 With Timezone: 2024-01-15 20:00:25 IST+0530
Comparison
| Method | Python Version | External Library | Best For |
|---|---|---|---|
pytz + tzlocal |
All versions | Yes | Complex timezone operations |
astimezone() |
3.6+ | No | Simple timezone conversion |
datetime.now() |
All versions | No | Quick local time display |
Conclusion
Use astimezone() without arguments for simple local timezone conversion in Python 3.6+. For complex timezone handling across different Python versions, use pytz with tzlocal.
