繁体   English   中英

时间数据“2021-06-10T18:39:41 10:00”与格式“%Y-%m-%dT%H:%M:%S %z”不匹配

[英]time data '2021-06-10T18:39:41 10:00' does not match format '%Y-%m-%dT%H:%M:%S %z'

我正在尝试将带有时区偏移量的日期时间字符串作为查询参数传递到 Django url 中,如下所示:

http://0.0.0.0:8080/coordinates/12.231/34.322/?obstime=2021-06-10T18:39:41+1000

我试图在视图中解析它,如下所示:

datetime.datetime.strptime(
    self.request.query_params.get('obstime'),
    "%Y-%m-%dT%H:%M:%S %z"
).isoformat()

所以我使用格式“%Y-%m-%dT%H:%M:%S %z”。

我认为这会起作用,但是我看到以下错误:

time data '2021-06-10T18:39:41 1000' does not match format '%Y-%m-%dT%H:%M:%S %z'

我试图寻找解决此错误的潜在方法,但到目前为止,一切都变得枯燥无味。

有谁知道我需要传递给 url 端点或datetime.datetime.strptime() function 的正确格式...

根据URL编码规则, +变成 (空间)。 如果要在 URL 中使用+号,则必须替换%2B

不好:

?obstime=2021-06-10T18:39:41+1000 
(this becomes ?obstime=2021-06-10T18:39:41 1000)

好的:

?obstime=2021-06-10T18:39:41%2B1000 
(this becomes ?obstime=2021-06-10T18:39:41+1000)

此外,您省略了空格符号。 也许如果你这样请求URL,它会正常处理。

?obstime=2021-06-10T18:39:41+%2B1000
(this becomes ?obstime=2021-06-10T18:39:41 +1000)

相关: 如何在 URL 中编码加号 (+)

我认为你需要'+'。

a_result = datetime.datetime.strptime('2021-06-10T18:39:41 +1000', '%Y-%m-%dT%H:%M:%S %z')
print('a result', a_result)

a result 2021-06-10 18:39:41+10:00

这将在没有空格的情况下解析,因此您需要在秒和时区之间添加一些标记。 我能够在印度的 5:30 时区完成这些工作

a_result = datetime.datetime.strptime('2021-06-10T18:39:41+05:30', '%Y-%m-%dT%H:%M:%S%z')
print(a_result)

2021-06-10 18:39:41+05:30

我还发现此Python 时区 '%z' 指令对于 datetime.strptime() 不可用

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM