Home > OS >  datetime.timestamp not the same as seconds since 1970
datetime.timestamp not the same as seconds since 1970

Time:09-22

I think I'm misunderstanding something regarding datetime timestamps. The descriptions I've read seem to say that a timestamp represents the Unix time (the number of seconds since 1970)

But when I run the following

import datetime
date = datetime.datetime(2020, 1 , 1, 0, 0, 0)

time1 = datetime.datetime.timestamp(date)
time2 = (date - datetime.datetime(1970,1,1,0,0,0)).total_seconds()

print(time1)
print(time2)

It prints:

1577862000.0
1577836800.0

Shouldn't these be the same? What am I misunderstanding?

CodePudding user response:

Timezones. The unix epoch is Jan 1st 1970 in UTC, but your local zone is not UTC, so when you create a "naive" datetime instance using datetime.datetime(1970,1,1,0,0,0) it's offset from the real unix epoch by several hours.

Attach tzinfo=datetime.timezone.utc to both of the created datetime instances, and you'll see equality.

Alternatively, use datetime.datetime.fromtimestamp(0) instead of datetime.datetime(1970,1,1,0,0,0) to get a "naive" datetime instance coincident with the epoch.

  • Related