windows python中unix纪元时间到windows纪元时间的转换

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8670610/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 18:45:50  来源:igfitidea点击:

Conversion of unix epoch time to windows epoch time in python

pythonwindowsunixdatetimeepoch

提问by user1040625

Quick question: Is there a pythonic (whether in the standard libraries or not) way to convert unix 32-bit epoch time to windows 64-bit epoch time and back again?

快速提问:是否有 Pythonic(无论是否在标准库中)方式将 unix 32 位纪元时间转换为 Windows 64 位纪元时间并再次转换?

回答by Fred Foo

You can convert a POSIX timestamp to a datetimewith

您可以将POSIX时间戳转换为datetime

>>> tstamp = 1325178061  # right about now
>>> from datetime import datetime
>>> datetime.fromtimestamp(tstamp)
datetime.datetime(2011, 12, 29, 18, 1, 1)

The fromtimestampnamed constructor accepts POSIX timestamps on all platforms (!).

fromtimestamp命名构造函数接受POSIX所有平台上的时间戳(!)。

Conversion to a Windows timestamp would be a matter of subtracting the Windows epoch, which Wikipedia saysis January 1, 1601, and converting the resulting timedeltato a number of seconds:

转换为 Windows 时间戳需要减去 Windows 纪元,维基百科称其为 1601 年 1 月 1 日,并将结果转换timedelta为秒数:

>>> W_EPOCH = datetime(1601, 1, 1)
>>> (datetime.fromtimestamp(tstamp) - W_EPOCH).total_seconds()
12969655261.0

Now you've got a floatthat you convert to intand store as a 64-bit quantity in whichever way you like.

现在您已经获得了一个float可以int以任何您喜欢的方式转换并存储为 64 位数量的 。

回答by Jitsusama

To convert from a Windows EPOCH timestamp to a datetimeobject (but not the other way around); here's a solution I came up with:

从 Windows EPOCH 时间戳转换为日期时间对象(但不是相反);这是我想出的解决方案:

from datetime import datetime, timezone
def convert_from(windows_timestamp: int) -> datetime:
    unix_epoch = datetime(1970, 1, 1, tzinfo=timezone.utc)
    windows_epoch = datetime(1601, 1, 1, tzinfo=timezone.utc)
    epoch_delta = unix_epoch - windows_epoch
    windows_timestamp_in_seconds = windows_timestamp / 10_000_000
    unix_timestamp = windows_timestamp_in_seconds - epoch_delta.total_seconds()

    return datetime.utcfromtimestamp(unix_timestamp)

This allows you to pass in the Windows timestamp as is and it will spit out a valid Python datetimeobject.

这允许您按原样传入 Windows 时间戳,它会输出一个有效的 Python日期时间对象。

NOTE: This is Python 3 specific.

注意:这是特定于 Python 3 的。