Reputation: 316
Rookie question:
the following works:
import time
# create time
dztupel = 1971, 1, 1, 0, 0, 1, 0, 0, 0
print(time.strftime("%d.%m.%Y %H:%M:%S", dztupel))
damals = time.mktime(dztupel)
# output
lt = time.localtime(damals)
wtage = ["Montag", "Dienstag", "Mittwoch","Donnerstag","Freitag","Samstag", "Sonntag"]
wtagnr = lt[6]
print("Das ist ein", wtage[wtagnr])
tag_des_jahres = lt[7]
print("Der {0:d}. Tag des Jahres".format(tag_des_jahres))
but:
dztupel = 1970, 1, 1, 0, 0, 1, 0, 0, 0
does not work,at least not at windows 10. edit: I get out of range error. But time should start at January 1st 1970 at 0 hour 0 min and 0 seconds. shouldn't it ?
Upvotes: 1
Views: 92
Reputation: 9846
In your second snippet, check out what the time.mktime()
function returns, given that dztupel
represents a datetime of 11:01am UTC on 1/1/1969 (shows as one hour ahead because of BST (i.e., UTC+0100) locally on my system):
>>> import time
>>> dztupel = 1970, 1, 1, 0, 0, 1, 0, 0, 0 # In BST locally for me, remember, so one hour less seconds than printed EPOCH seconds
>>> time.mktime(dztupel) # This command
-3599.0 # seconds after (i.e., before as is negative) 1/1/1970 UTC0000
It's negative because EPOCH time (which time.mktike
is printing, in seconds) starts at UTC midnight on 1/1/1970:
>>> dztupel = 1970, 1, 1, 1, 0, 0, 0, 0, 0 # 1/1/1970 BST0100 == 1/1/1970 UTC0000
>>> time.mktime(dztupel)
0.0 # seconds after 1/1/1970 UTC0000
Hence 0.0
, as it's 0 seconds since dztupel = 1970, 1, 1, 1, 0, 0, 0, 0, 0
since BST 0100 on 1/1/1970, or since UTC midnight on 1/1/1970.
Really, we want to print as UTC, so instead of time.localtime()
, use time.gmtime()
:
>>> dztupel = 1970, 1, 1, 0, 0, 1, 0, 0, 0
>>> time.gmtime(time.mktime(dztupel))
time.struct_time(tm_year=1969, tm_mon=12, tm_mday=31, tm_hour=23, tm_min=0, tm_sec=1, tm_wday=2, tm_yday=365, tm_isdst=0)
Then use strftime()
to format it:
>>> gmt = time.gmtime(time.mktime(dztupel))
>>> time.strftime('%Y-%m-%d %H:%M:%S', gmt)
'1969-12-31 23:00:01'
Upvotes: 1