From 0675c6c599d0b43b8e278a57fbcb16f0a78cdcaf Mon Sep 17 00:00:00 2001 From: Wirawan Purwanto Date: Wed, 23 Oct 2013 13:04:48 -0400 Subject: [PATCH] * Added wpylib.datetime.utime_to_iso() function. --- datetime.py | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/datetime.py b/datetime.py index 9a9182b..b809359 100644 --- a/datetime.py +++ b/datetime.py @@ -37,3 +37,31 @@ def shift_time(t, dt, localtime=True): else: return time.gmtime(t1) +def utime_to_iso(t, local=True): + """Converts UNIX time (seconds since Epoch) to ISO-formatted time string. + + In order to ease time computation/conversion, + we will use numeric TZ shift (+/-HH:MM) instead of + letter TZ code (EDT, EST, GMT, etc). + """ + from time import localtime, gmtime, strftime, timezone + if local: + tt = localtime(t) + dtz = -timezone + tt.tm_isdst * 3600 + # hopefully dtz is divisible by 60 + # It would be silly for a gov't to make its time + # differ by seconds to GMT! + dsec = abs(dtz) % 60 + dmin = abs(dtz // 60) % 60 + dhr = dtz // 3600 + if dsec == 00: + sdtz = " %+03d:%02d" % (dhr, dmin) + else: + sdtz = " %+03d:%02d:%02d" % (dhr, dmin, dsec) + else: + tt = gmtime(t) + sdtz = " +00:00" + # Numeric timezone offset is created by hand + # because I don't want to use %Z, nor do I want to use + # "%z" (which did not work in python) + return strftime("%Y-%m-%d %H:%M:%S", tt) + sdtz