时间.ctimePython中的(secs)函数提供了与在C中使用DateTime不同的日期#

2024-05-14 05:54:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数字代表从纪元开始的秒数,1490976000。 在python3.5中,调用时间.ctime(1490976000),我收到“2017年3月31日星期五09:00:00”

但是在.NET C中,当我使用以下代码时

DateTime initDT = new DateTime(1970, 1, 1, 0, 0, 0);
Console.WriteLine(initDT.AddSeconds(1490976000).ToString());

我有“3/31/2017 4:00:00 PM”,正如您所见,时间与python不同,有人知道为什么吗?在


Tags: 代码newdatetimenet时间代表数字console
2条回答

不精通python,但在阅读文档时,它声明:

time.ctime([secs])

Convert a time expressed in seconds since the epoch to a string representing local time. If secs is not provided or None, the current time as returned by time() is used. ctime(secs) is equivalent to asctime(localtime(secs)). Locale information is not used by ctime().

因此,考虑到这些信息,我们需要在.NET中执行相同的操作:

DateTime initDT = new DateTime(1970, 1, 1, 0, 0, 0).ToLocalTime();
var result = initDT.AddSeconds(1490976000);

这个Python代码与您从C获得的代码相匹配:

>>> from datetime import *
>>> datetime(1970, 1, 1) + timedelta(seconds=1490976000)
datetime.datetime(2017, 3, 31, 16, 0)

这是UTC的正确答案。但是ctime()从UTC转换到您的本地时区。

如果您想要UTC,并且不想使用Python的datetime,请改用Python的time.gmtime()

^{pr2}$

相关问题 更多 >