1

I want to capture a timestamp and the current timezone and serialize it into a file (in JSON or YAML, but that's not really my question) for later retrieval on a different computer.

The timestamp is easy, I'll just use time.time().

For getting the current timezone, I read another SO question and it seems appropriate to use dateutil.tz.tzlocal to get the current timezone.

Now I just need to figure out how to serialize it. The name is easy, that's just a string, but the offset seems to be weird; I was expecting just a number:

import time
import datetime
import dateutil

now = datetime.datetime.utcfromtimestamp(time.time())
tzlocal = dateutil.tz.tzlocal()
print tzlocal.tzname(now)
print tzlocal.utcoffset(now)

but this prints

US Mountain Standard Time
-1 day, 17:00:00

and the result of utcoffset appears to be an object. How do I just get the number?

Jason S
  • 184,598
  • 164
  • 608
  • 970

2 Answers2

1

Oh, never mind, tzlocal.utcoffset(now) returns a datetime.timedelta and I can just call total_seconds():

import time
import datetime
import dateutil
import json

now = datetime.datetime.utcfromtimestamp(time.time())
tzlocal = dateutil.tz.tzlocal()
info_str = json.dumps(dict(name=tzlocal.tzname(now),
                       offset=tzlocal.utcoffset(now).total_seconds()))
print info_str

which prints (on my PC)

{"name": "US Mountain Standard Time", "offset": -25200.0}
Jason S
  • 184,598
  • 164
  • 608
  • 970
1

I'm not sure what your application is but as a default I recommend serializing to ISO 8601 timestamps with a time zone offset. Even better, convert to UTC first... this makes things easier for humans who happen to browse the serialized data, because they don't have to do the date math in their head.

There may be performance reasons for sticking with numeric timestamps, but I'd want proof this was a bottleneck in my application before giving up the human-readable bonus of ISO timestamps.

ben author
  • 2,855
  • 2
  • 25
  • 43