Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to `strftime` having timezone adjusted?

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?

like image 911
Morgan Wilde Avatar asked May 23 '13 19:05

Morgan Wilde


People also ask

How do I add time zones to Strftime?

Use the syntax string_datetime + " " + timezone with string_datetime as a result of datetime. datetime. strftime() to add the timezone.

What does pytz timezone do?

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.

What is the meaning of Strftime for a datetime variable?

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.


1 Answers

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.

like image 156
unutbu Avatar answered Oct 01 '22 15:10

unutbu