views:

87

answers:

3

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?

+1  A: 

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'
S.Mark
How? There is no way how to get timezone offset, and %Z gets just the timezone name..?
TarGz
@TarGz - time.timezone has offset of localtime zone in secs, you may want to combine two to make it work
S.Mark
It seems, %z is pltaform dependent
TarGz
@TarGz, yeah, its need time.tzset(), and its only available in Unix
S.Mark
A: 

The datetime module supports timezones and myriad ways of formatting.

msw
Yes, I know but I don't understand what the docs say and the examples are confusing. All I want is to know the local timezone, respecting daylight saying.
TarGz
+2  A: 
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)))
badp
This just got me "20100321142049-01'00'" :)
badp
Exactly what I wanted!
TarGz
Oh, no! There is a bug. Say, someone lives in Italy, the timezone then is +01'00', not -01'00'...
TarGz
In docs, there is an examle and there they say "-time.altzone" and "-time.timezone". Hmm....
TarGz
Anyways, thanks a lot!
TarGz
Whooops. Fixed.
badp