← Back to team overview

openstack team mailing list archive

i'm easily confused about time and timezones

 

hi,

Looking at nova/utils.py I *think* that utcnow() is right but
utcnow_ts() is incorrect. The former does give UTC, the latter
unfortunately changes it to localtime. I haven't written a test in
nova, but I extracted the code and wrote a little demo that I *think*
shows the right way to do it, using calendar.timegm().

I'd appreciate help understanding / verifying / cluing me in on if I'm
barking up the right tree. :-)

#!/usr/bin/env python
import time, datetime, calendar
def utcnow():
    return datetime.datetime.utcnow()
def utcnow_ts( ts ):
    return time.mktime( ts.timetuple() )
def dt_to_seconds( dt ):
    return int( calendar.timegm( dt.timetuple() ) )
def seconds_to_dt( seconds ):
    return datetime.datetime.utcfromtimestamp( seconds )
now_dt = utcnow()
now_ts = utcnow_ts( now_dt )
now_s = dt_to_seconds( now_dt )
nova_dt2 = seconds_to_dt( now_ts )
cal_dt2 = seconds_to_dt( now_s )
print now_dt
print now_ts
print nova_dt2
print now_s
print cal_dt2