1 python console time datetime python-3.x
我在尝试在 python 上打印时间时遇到问题。这是我最近尝试的代码:
from time import gmtime, strftime
strftime("%Y-%m-%d %H:%M:%S", gmtime())
Run Code Online (Sandbox Code Playgroud)
有什么问题?你的代码有效
? python
Python 3.7.0 (default, Jun 28 2018, 08:04:48) [MSC v.1912 64 bit (AMD64)] :: Anaconda, Inc. on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from time import gmtime, strftime
>>> strftime("%Y-%m-%d %H:%M:%S", gmtime())
'2019-02-14 13:56:02'
>>> strftime("%H:%M:%S", gmtime())
'13:56:16'
>>>
Run Code Online (Sandbox Code Playgroud)
编辑:
这段代码在终端中运行良好——正如@ForceBru 提到的,如果你在脚本中运行它,你将需要使用打印功能来显示结果 strftime
from time import gmtime, strftime
print(strftime("%Y-%m-%d %H:%M:%S", gmtime()))
> '2019-02-14 13:56:02'
print(strftime("%H:%M:%S", gmtime()))
> '13:56:16'
Run Code Online (Sandbox Code Playgroud)
您的原始代码是正确的,但缺少打印语句。
from time import gmtime, strftime
print (strftime("%Y-%m-%d %H:%M:%S", gmtime()))
# output
2019-02-14 14:56:18
Run Code Online (Sandbox Code Playgroud)
以下是获取协调世界时 (UTC)/格林威治标准时间 (GMT) 时间戳的其他一些方法。
from datetime import datetime
from datetime import timezone
current_GMT_timestamp = datetime.utcnow()
print (current_GMT_timestamp)
# output
2019-02-14 14:56:18.827431
# milliseconds removed from GMT timestamp
reformatted_GMT_timestamp = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')
print (reformatted_GMT_timestamp)
# output
2019-02-14 14:56:18
# GMT in ISO Format
current_ISO_GMT_timestamp = datetime.now(timezone.utc).isoformat()
print (current_ISO_GMT_timestamp)
# output
2019-02-14T14:56:18.827431+00:00
Run Code Online (Sandbox Code Playgroud)