Python time模块中的time.time()返回的是系统时间还是UTC时间?
当前回答
time.time()函数的作用是:以浮点数的形式返回自epoch开始的秒数。请注意,“epoch”定义为UTC时间1970年1月1日的开始。因此,epoch是根据UTC来定义的,并建立了一个全局时间点。无论你在地球上的什么地方,"seconds past epoch" (time.time())在同一时刻返回相同的值。
下面是我在计算机上运行的一些示例输出,并将其转换为字符串。
>>> import time
>>> ts = time.time()
>>> ts
1355563265.81
>>> import datetime
>>> datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
'2012-12-15 01:21:05'
>>>
ts变量是以秒为单位返回的时间。然后,我使用datetime库将其转换为人类可读的字符串。
其他回答
我最终决定:
>>> import time
>>> time.mktime(time.gmtime())
1509467455.0
time.time()函数的作用是:以浮点数的形式返回自epoch开始的秒数。请注意,“epoch”定义为UTC时间1970年1月1日的开始。因此,epoch是根据UTC来定义的,并建立了一个全局时间点。无论你在地球上的什么地方,"seconds past epoch" (time.time())在同一时刻返回相同的值。
下面是我在计算机上运行的一些示例输出,并将其转换为字符串。
>>> import time
>>> ts = time.time()
>>> ts
1355563265.81
>>> import datetime
>>> datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
'2012-12-15 01:21:05'
>>>
ts变量是以秒为单位返回的时间。然后,我使用datetime库将其转换为人类可读的字符串。
答案可能是两者都不是,也可能都是。
neither: time.time() returns approximately the number of seconds elapsed since the Epoch. The result doesn't depend on timezone so it is neither UTC nor local time. Here's POSIX defintion for "Seconds Since the Epoch". both: time.time() doesn't require your system's clock to be synchronized so it reflects its value (though it has nothing to do with local timezone). Different computers may get different results at the same time. On the other hand if your computer time is synchronized then it is easy to get UTC time from the timestamp (if we ignore leap seconds): from datetime import datetime utc_dt = datetime.utcfromtimestamp(timestamp)
有关如何在各种Python版本中从UTC时间获取时间戳,请参阅如何根据UTC获取从epoch开始转换为秒的日期?
要使用datetime库获取本地时间戳,请使用Python 3.x
#wanted format: year-month-day hour:minute:seconds
from datetime import datetime
# get time now
dt = datetime.now()
# format it to a string
timeStamp = dt.strftime('%Y-%m-%d %H:%M:%S')
# print it to screen
print(timeStamp)
根据来自#squiguy的答案,为了获得一个真实的时间戳,我将从float类型转换它。
>>> import time
>>> ts = int(time.time())
>>> print(ts)
1389177318
至少这是一个概念。
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 使用try和。Python中的if
- 如何在Python中获得所有直接子目录