I store my datetime int UTC like so:
import pytz, datetime
timeUTC = datetime.datetime(2013, 5, 23, 19, 27, 50, 0)
timezoneLocal = pytz.timezone('Europe/Vilnius')
timeLocal = timezoneLocal.localize(timeUTC)
But when I try to print it, it just gives me regular UTC hours
>>> timeLocal.strftime('%H:%M:%S')
'19:27:50'
I would expect this to return '22:27:50'
since this is the local time (pytz.timezone('Europe/Vilnius')
is +3 at the moment). What am I missing here?
Use the syntax string_datetime + " " + timezone with string_datetime as a result of datetime. datetime. strftime() to add the timezone.
The pytz module allows for date-time conversion and timezone calculations so that your Python applications can keep track of dates and times, while staying accurate to the timezone of a particular location.
The strftime() function is used to convert date and time objects to their string representation. It takes one or more input of formatted code and returns the string representation. Syntax : strftime(format) Returns : It returns the string representation of the date or time object.
Localize the date string as a UTC datetime, then use astimezone
to convert it to the local timezone.
import pytz, datetime
timeUTC = datetime.datetime(2013, 5, 23, 19, 27, 50, 0)
timezoneLocal = pytz.timezone('Europe/Vilnius')
utc = pytz.utc
timeLocal = utc.localize(timeUTC).astimezone(timezoneLocal)
print(timeLocal)
# 2013-05-23 22:27:50+03:00
localize
does not convert datetimes, it interprets the date string as though it were written in that timezone. localize
builds a timezone-aware datetime out of a naive datetime (such as timeUTC
). astimezone
converts timezone-aware datetimes to other timezones.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With