如何解决日期时间
我的问题是 ValueError
正在上升,因为我的日期时间字符串格式错误。
# month is given. Sometimes with seconds as '.Z' (int) and sometimes as '.0000Z' (float)
try:
next_month = datetime.datetime.strptime(month,'%Y-%m-%dT%H:%M:%S.%fZ')
except ValueError:
print('asd')
next_month = datetime.datetime.strptime(month,'%Y-%m-%dT%H:%M:%SZ')
next_month += relativedelta.relativedelta(months=1)
Django 错误跟踪堆栈很难复制,但这里是 raise
:
raise ValueError("time data %r does not match format %r" %(data_string,format))
有了这个,我很确定,它是关于 datetime
。 (关于日期时间,呵呵)
发现了有关此主题的一些问题,但没有提出任何解决方案。他们中的大多数人都没有在 try-except
中放置产生此错误的确切代码。
问题是:为什么 ValueError
没有被处理?
编辑:报告片段:
以下代码在 PyCharm 中运行(python3.7,同上),没有重现这个错误。
import datetime
if __name__ == "__main__":
d1 = '2021-03-24T11:20:33Z'
d2 = "2021-03-10T20:45:01.036000Z"
d = d2 # for quick change
try:
next_month = datetime.datetime.strptime(
d,'%Y-%m-%dT%H:%M:%S.%fZ')
print('try: ',next_month)
except ValueError:
next_month = datetime.datetime.strptime(
d,'%Y-%m-%dT%H:%M:%SZ')
print('except: ',next_month)
编辑 2:
在 Django 错误页面中:ValueError at /api/sessions_stats_csv/
Traceback (most recent call last):
django_server_dev | File "/usr/local/lib/python3.9/site-packages/django/core/handlers/exception.py",line 47,in inner
django_server_dev | response = get_response(request)
django_server_dev | File "/usr/local/lib/python3.9/site-packages/django/core/handlers/base.py",line 179,in _get_response
django_server_dev | response = wrapped_callback(request,*callback_args,**callback_kwargs)
django_server_dev | File "/app/label_it/rest_api/statistics_view.py",line 334,in AllSessionsDetailsCSV
django_server_dev | rows = ExtractSessionsForUser(item,params['for_month'])
django_server_dev | File "/app/label_it/rest_api/statistics_view.py",line 485,in ExtractSessionsForUser
django_server_dev | format_date = datetime.datetime.strptime(
django_server_dev | File "/usr/local/lib/python3.9/_strptime.py",line 568,in _strptime_datetime
django_server_dev | tt,fraction,gmtoff_fraction = _strptime(data_string,format)
django_server_dev | File "/usr/local/lib/python3.9/_strptime.py",line 349,in _strptime
django_server_dev | raise ValueError("time data %r does not match format %r" %
django_server_dev | ValueError: time data '2021-03-24T11:20:33Z' does not match format '%Y-%m-%dT%H:%M:%S.%fZ'
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。