Search code examples
pythondatetimeboostepoch

Boost / Python unix timestamps don't match


Python 2.6:

import pytz
import time
import datetime
time.mktime(datetime.datetime(1990, 1, 1, tzinfo=pytz.utc).timetuple())

Result:

631148400.0

Boost 1.46:

auto a = boost::posix_time::ptime(boost::gregorian::date(1990, 1, 1));
auto b = boost::posix_time::ptime(boost::gregorian::date(1970, 1, 1)); // unix epoch
boost::posix_time::time_duration x = a - b;
std::cerr << x.total_seconds() << std::endl;

Result:

631152000

Difference is 3600 (1 hour). Why?


Solution

  • For the example below I set my time zone to GMT-01:

    >>> import datetime, time, pytz
    
    >>> tz = pytz.FixedOffset(-60)
    >>> dt = datetime.datetime(1990, 1, 1, tzinfo=pytz.utc)
    
    >>> tm = dt.astimezone(tz).timetuple(); tm
    time.struct_time(tm_year=1989, tm_mon=12, tm_mday=31, tm_hour=23, tm_min=0, tm_s
    ec=0, tm_wday=6, tm_yday=365, tm_isdst=0)
    
    >>> time.mktime(tm)
    631152000.0
    

    mktime takes a time tuple based on local time, so the UTC datetime object has to first be adjusted to local time.