Joshua Olson
Joshua Olson

Reputation: 3803

Why do I get different timestamps in python on different machines

I have a dictionary which comes from a DB and I know that create_dt and install_ts match.

untimed = {'install_id': 399142,  'create_dt': datetime.datetime(2013, 7, 7, 0, 33, 2), 'install_ts': 1373157182}

And on QA when I run the following code everything is correct

>>(mktime(untimed['create_dt'].timetuple()) - untimed['install_ts']) / 3600
0.0

But when I run it locally on my laptop I get (Locally I'm in PST)

>>(mktime(untimed['create_dt'].timetuple()) - untimed['install_ts']) / 3600
7.0

Why am I not getting the same timestamp? I know that create_dt is in UTC, but locally it is forcing it to PST (-700).

Note: I've narrowed the issue down to this, but the full problem is I'm getting the wrong timestamp when I try

mktime(datetime.strptime(install['click_date'],'%Y-%m-%d %H:%M:%S').timetuple())

More specifically why in Convert python datetime to epoch with strftime does

>>> datetime.datetime(2012,04,01,0,0).strftime('%s')  # This is equivalent to my issues above
'1333234800'
>>> (datetime.datetime(2012,04,01,0,0) - datetime.datetime(1970,1,1)).total_seconds()
1333238400.0

give different values?

Upvotes: 3

Views: 1197

Answers (1)

hago
hago

Reputation: 1710

An unix timestamp is an offset value between a point in time line and the epoch, it's nothing to do with timezone. When it's converted to a human readable string like '%Y-%m-%d %H:%M:%S' that doesn't include any timezone information, python assumes that you want to use local timezone setting.

When you run this

datetime.strptime(install['click_date'],'%Y-%m-%d %H:%M:%S')

you get a datetime object, which doesn't contain any timezone information and can be only explained as local time. If you run it on an UTC server the object is explained as '2013-07-07 00:33:02 UTC', if on your PST server it is '2013-07-07 00:33:02 PST', they are different points in time line therefore they have different unix timestamp values. To make it treat install['click_date'] as UTC time, timezone offset needs to be added:

time.mktime(datetime.datetime.strptime(install['click_date'], '%Y-%m-%d %H:%M:%S %Z').timetuple()) + time.timezone

on my CST server(timezone 0800),

>>> time.mktime(datetime.datetime.strptime('2013-07-07 00:33:02', '%Y-%m-%d %H:%M:%S').timetuple()) 

1373128382.0

>>> time.mktime(datetime.datetime.strptime('2013-07-07 00:33:02', '%Y-%m-%d %H:%M:%S').timetuple()) + time.timezone

1373099582.0

the first call takes '2013-07-07 00:33:02' as local time, the second one takes it as UTC time.

Upvotes: 3

Related Questions