简体   繁体   English

如何使用python将Unix时间戳转换为DateTime,反之亦然?

[英]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. unix 时间戳是一个int ,它给出自1970 年 1 月 1 日(UTC)以来的秒数。

Is there a way to convert the .NET timestamp to unix timestamp using python ?有没有办法使用 python 将 .NET 时间戳转换为 unix 时间戳? or can this only be done in C# ?或者这只能在 C# 中完成? Any help would be greatly appreciated.任何帮助将不胜感激。

Similar question: How to convert a Unix timestamp to DateTime and vice versa?类似问题: 如何将 Unix 时间戳转换为 DateTime,反之亦然? this contains how to do this in CI am looking for a way to do this in python 34这包含如何在 CI 中执行此操作我正在寻找一种在 python 34 中执行此操作的方法

Is there a way to convert the .NET timestamp to unix timestamp using python?有没有办法使用python将.NET时间戳转换为unix时间戳?

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:很容易在表示 UTC 时间的 datetime 对象和时间戳之间进行转换:

#!/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 .有关如何在较旧的 Python 版本上实现// timedelta()请参阅totimestamp()函数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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