21
votes

I need to generate a local timestamp in a form of YYYYMMDDHHmmSSOHH'mm'. That OHH'mm' is one of +, -, Z and then there are hourhs and minutes followed by '.

Please, how do I get such a timestamp, denoting both local time zone and possible daylight saving?

2
Where did you look for time formatting? What did you try? What errors did you get? - S.Lott
I read std lib docs, and they are confusing what timezones goes... - TarGz
"confusing"? Could mean anything. To help others with the same problem, could you provide the quote or link that confused you? - S.Lott

2 Answers

32
votes
import time

localtime   = time.localtime()
timeString  = time.strftime("%Y%m%d%H%M%S", localtime)

# is DST in effect?
timezone    = -(time.altzone if localtime.tm_isdst else time.timezone)
timeString += "Z" if timezone == 0 else "+" if timezone > 0 else "-"
timeString += time.strftime("%H'%M'", time.gmtime(abs(timezone)))
8
votes

time.strftime will do for that,

And in linux, %z will just give you -HHMM format if environment variable is properly set.

>>> os.environ['TZ'] = 'EST'
>>> time.strftime('%x %X %z')
'03/21/10 08:16:33 -0500'