Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/301.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/haskell/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python`strtime`missing";";及;Z";什么时候打印?_Python_Utc_Python Datetime - Fatal编程技术网

Python`strtime`missing";";及;Z";什么时候打印?

Python`strtime`missing";";及;Z";什么时候打印?,python,utc,python-datetime,Python,Utc,Python Datetime,我错过了什么 这是为什么… import datetime start_date = '2020-10-01T00:00:00Z' start_date_obj = datetime.datetime.strptime(start_date, '%Y-%m-%dT%H:%M:%SZ') print(start_date_obj) …结果:2020-10-01 00:00:00 …而不是:2020-10-01T00:00:00Z 输出中的“T”和“Z”在哪里?忽略。显然,我需要将dateti

我错过了什么

这是为什么…

import datetime

start_date = '2020-10-01T00:00:00Z'
start_date_obj = datetime.datetime.strptime(start_date, '%Y-%m-%dT%H:%M:%SZ')

print(start_date_obj)
…结果:
2020-10-01 00:00:00

…而不是:
2020-10-01T00:00:00Z


输出中的“T”和“Z”在哪里?

忽略。显然,我需要将
datetime
对象转换回string(?),以便更好地打印

import datetime

start_date = '2020-10-01T00:00:00Z'
start_date_obj = datetime.datetime.strptime(start_date, '%Y-%m-%dT%H:%M:%SZ')
start_date_printable = datetime.datetime.strftime(start_date_obj, '%Y-%m-%dT%H:%M:%SZ')

print(start_date_printable)

结果为:
2020-10-01T00:00:00Z
Z表示UTC,因此您应该使用
strtime
%Z
指令解析到aware datetime对象:

from datetime import datetime

s = '2020-10-01T00:00:00Z'
dt = datetime.strptime(s, '%Y-%m-%dT%H:%M:%S%z')
print(dt)
# 2020-10-01 00:00:00+00:00
或者从ISOFORMAT
中选择一点:

在转换回字符串时,可以执行相同的操作:

out = dt.isoformat().replace('+00:00', 'Z')
print(out)
# 2020-10-01T00:00:00Z
strftime
不会为您提供
Z
,但例如
UTC

out = dt.strftime('%Y-%m-%dT%H:%M:%S %Z')
print(out)
# 2020-10-01T00:00:00 UTC

请注意,当您调用
print(datetime\u对象)
时,将调用datetime对象的
\uu str\uuu
方法-这恰好为您提供了以空格作为日期/时间分隔符的isoformat。这只是展示的问题,仅此而已。如果您想要特定格式的字符串,请参阅我的答案。这是否回答了您的问题?
out = dt.strftime('%Y-%m-%dT%H:%M:%S %Z')
print(out)
# 2020-10-01T00:00:00 UTC