简体   繁体   中英

How to convert a Unix timestamp to DateTime and vice versa with python?

A unix timestamp is an int which gives the number of seconds since January 1, 1970, UTC.

Is there a way to convert the .NET timestamp to unix timestamp using python ? or can this only be done in C# ? Any help would be greatly appreciated.

Similar question: How to convert a Unix timestamp to DateTime and vice versa? this contains how to do this in CI am looking for a way to do this in python 34

Is there a way to convert the .NET timestamp to unix timestamp using python?

posix_epoch_as_dotnet = 621355968000000000

# convert .NET timestamp to POSIX timestamp
posix_timestamp = (130900894153614080 - posix_epoch_as_dotnet) // 10**7

It is easy to convert between a datetime object that represents time in UTC and the timestamps:

#!/usr/bin/env python
from datetime import datetime, timedelta

dotnet_epoch = datetime(1, 1, 1)
posix_epoch = datetime(1970, 1, 1)
utc_time = dotnet_epoch + timedelta(microseconds=dotnet_timestamp//10)
utc_time = posix_epoch + timedelta(seconds=posix_timestamp)

and back:

posix_timestamp = (utc_time - posix_epoch) // timedelta(seconds=1)
dotnet_timestamp = 10 * (utc_time - dotnet_epoch) // timedelta(microseconds=1)

See totimestamp() function on how to implement // timedelta() on older Python versions .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM