how to create datetime from a negative epoch in Python

Deadly 提交于 2019-12-01 17:46:32

This works for me:

datetime.datetime(1970, 1, 1) + datetime.timedelta(seconds=(-3739996800000/1000))

datetime.datetime(1851, 6, 27, 0, 0)

This would have been better asked on StackOverflow since it is more Python specific than it is GIS-specific.

if timestamp < 0:
    return datetime(1970, 1, 1) + timedelta(seconds=timestamp)
else:
    return datetime.utcfromtimestamp(timestamp)

You can accomplish this using the datetime module's datetime and timedelta functions.

The other answers divide the timestamp by 1000 to convert milliseconds to seconds. This is unnecessary, since the timedelta function can take milliseconds directly as a parameter. It might therefore be cleaner to do something like this:

datetime.datetime(1970, 1, 1) + datetime.timedelta(milliseconds=-3739996800000)

which gives datetime.datetime(1851, 6, 27, 0, 0), as you'd expect.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!