python time.strftime %z is always zero instead of timezone offset

2024/11/15 8:30:42
>>> import time
>>> t=1440935442
>>> time.strftime("%Y/%m/%d-%H:%M:%S %z",time.gmtime(t))
'2015/08/30-11:50:42 +0000'
>>> time.strftime("%Y/%m/%d-%H:%M:%S %z",time.localtime(t))
'2015/08/30-13:50:42 +0000'

The offset stays the same +0000, but I expect '2015/08/30-13:50:42 +0200'

The timezone is correct, as the command is interpreting capital %Z as it should

>>> time.strftime("%Y/%m/%d-%H:%M:%S %Z",time.localtime(t))
'2015/08/30-13:50:42 CEST'

Unix date works like I want

$ date -u --date @1440935442 +"%Y/%m/%d-%H:%M:%S %z"
2015/08/30-11:50:42 +0000
$ date --date @1440935442 +"%Y/%m/%d-%H:%M:%S %z"
2015/08/30-13:50:42 +0200
Answer

As documented:

Most of the functions defined in this module call platform C libraryfunctions with the same name. It may sometimes be helpful to consultthe platform documentation, because the semantics of these functionsvaries among platforms.

and:

Additional directives may be supported on certain platforms, but onlythe ones listed here have a meaning standardized by ANSI C. To see thefull set of format codes supported on your platform, consult thestrftime(3) documentation.

...

The use of %Z is now deprecated, but the %z escape that expands to thepreferred hour/minute offset is not supported by all ANSI C libraries.

time.strftime() uses C strftime() and therefore the behavior is platform-dependent. %z should work on POSIX but %z may return the same result as %Z on Windows. %z is not documented on Python 2 and therefore time module should return whatever C strftime() returns on the given platform without any changes.

The same code works in Python 3 on my machine:

>>> import time
>>> t = 1440935442
>>> time.strftime("%Z%z", time.gmtime(t))
'GMT+0000'
>>> time.strftime("%Z%z", time.localtime(t)) 
'CEST+0200'

Your issue seems to be Python 2 specific:

>>> import time
>>> t = 1440935442
>>> time.strftime("%Z%z", time.gmtime(t))
'CET+0000'
>>> time.strftime("%Z%z", time.localtime(t))
'CEST+0000'

Note: time.strftime('%Z%z') returns 'CEST+0200' on both Python 2 and 3. The difference might be explained by the absence of tm_zone, tm_gmtoff attributes in Python <3.3. Neither time.gmtime() nor time.localtime() provide timezone info on Python 2 (apart from tm_isdst that is why time.gmtime() leads to CET). time.strftime('%Z%z') uses C localtime() and therefore it may provide tm_zone, tm_gmtoff even on Python 2.

If you need portable behavior and to support timezones that might have different tzname, utc offset in the past; you could use pytz tzinfo objects (e.g., via tzlocal module) that provide access to the historical timezone database:

>>> from datetime import datetime
>>> import tzlocal # $ pip install tzlocal
>>> datetime.fromtimestamp(1440935442, tzlocal.get_localzone()).strftime('%Z%z')
'CEST+0200'
https://en.xdnf.cn/q/71796.html

Related Q&A

Python: Nested for loops or next statement

Im a rookie hobbyist and I nest for loops when I write python, like so:dict = {key1: {subkey/value1: value2} ... keyn: {subkeyn/valuen: valuen+1}}for key in dict:for subkey/value in key:do it to itIm a…

How to install cython an Anaconda 64 bits with Windows 10?

Its all in the title, does someone have a step by step method to install cython and run it on Anaconda 64 bits on Windows 10? I search for hours and there are a lot of tutorials... For things that I w…

Using DictWriter to write a CSV when the fields are not known beforehand

I am parsing a large piece of text into dictionaries, with the end objective of creating a CSV file with the keys as column headers. csv.DictWriter(csvfile, fieldnames, restval=, extrasaction=raise, di…

How to Save io.BytesIO pdfrw PDF into Django FileField

What I am trying to do is basically:Get PDF from URL Modify it via pdfrw Store it in memory as a BytesIO obj Upload it into a Django FileField via Model.objects.create(form=pdf_file, name="Some n…

Which python static checker can catch forgotten await problems?

Code: from typing import AsyncIterableimport asyncioasync def agen() -> AsyncIterable[str]:print(agen start)yield 1yield 2async def agenmaker() -> AsyncIterable[str]:print(agenmaker start)return …

Tkinter : Syntax highlighting for Text widget

Can anyone explain how to add syntax highlighting to a Tkinter Text widget ?Every time the program finds a matching word, it would color that word to how I want. Such as : Color the word tkinter in pi…

how to use pkgutils.get_data with csv.reader in python?

I have a python module that has a variety of data files, (a set of csv files representing curves) that need to be loaded at runtime. The csv module works very well # curvefile = "ntc.10k.csv"…

How to make celery retry using the same worker?

Im just starting out with celery in a Django project, and am kinda stuck at this particular problem: Basically, I need to distribute a long-running task to different workers. The task is actually broke…

Make an AJAX call to pass drop down value to the python script

I want to pass the selected value from dropdown which contains names of databases and pass it to the python script in the background which connects to the passed database name. Following is the ajax co…

PyLint 1.0.0 with PyDev + Eclipse: include-ids option no longer allowed, breaks Eclipse integration

As noted in this question: How do I get Pylint message IDs to show up after pylint-1.0.0?pylint 1.0.0 no longer accepts "include-ids" option. (It returns "lint.py: error: no such optio…