darkhorse
darkhorse

Reputation: 8722

How to print out the timezone for a time object in Python?

I am trying to print out a time with the timezone info as a string in the format '%H:%M:%S%z'. To do this, I am doing the following:

import pytz
import datetime

tz = pytz.timezone('Africa/Cairo')
time = datetime.datetime.strptime('14:24:41', '%H:%M:%S').time()
time = time.replace(tzinfo=tz)

print(time.strftime('%H:%M:%S%z'))

The result I get is simply '14:24:41', even after replacing the tzinfo. What am I doing wrong here?

EDIT This question is not a duplicate, as the other one does not explain why the timezone is not being printed using the strftime() method.

Upvotes: 3

Views: 1214

Answers (1)

Andrew F
Andrew F

Reputation: 2950

From the datetime package, %z is

UTC offset in the form ±HHMM[SS[.ffffff]] (empty string if the object is naive).

and

For a naive object, the %z and %Z format codes are replaced by empty strings. For an aware object:

%z

utcoffset() is transformed into a string of the form ±HHMM[SS[.ffffff]], where HH is a 2-digit string giving the number of UTC offset hours, MM is a 2-digit string giving the number of UTC offset minutes, SS is a 2-digit string giving the number of UTC offset seconds and ffffff is a 6-digit string giving the number of UTC offset microseconds.

Using your sample code, time.utcoffset() returns empty.

Edit, with a fix

You probably want to use the .localize() method, but to do so you would need to convert the string to a datetime.datetime and not the datetime.time object. This makes sense in a way: Wednesday at 0100 in Tokyo, is Tuesday 1700 in Berlin.

import pytz
import datetime

tz = pytz.timezone('Africa/Cairo')
dt = datetime.datetime.strptime('14:24:41', '%H:%M:%S')
time = tz.localize(dt)

print(time.strftime('%H:%M:%S%z'))

Upvotes: 2

Related Questions