- 1 year ago
Python UTC to local
Comment
1 / 1
To convert a UTC datetime to local timezone in Python, you can use the pytz
library along with the datetime
module. Here's an example:
pythonimport datetime
import pytz
# Get the current UTC time
utc_now = datetime.datetime.now(pytz.utc)
# Convert UTC time to local timezone
local_timezone = pytz.timezone('Your_Local_Timezone')
local_time = utc_now.astimezone(local_timezone)
# Print the local time
print(local_time)
In the code above, replace 'Your_Local_Timezone'
with the name of your local timezone, such as 'Asia/Kolkata'
, 'America/New_York'
, or 'Europe/London'
. You can find a list of valid timezone names in the official pytz documentation.
The astimezone()
method converts the UTC time (utc_now
) to the specified local timezone (local_timezone
), and the resulting local_time
object represents the local datetime.
Note: Ensure that you have the pytz
library installed before running the code. You can install it using pip install pytz
.