ValueError时间数据'2016年3月11日星期五15:59:57'与格式'%a%b%d%H:%M:%S%Z%Y'不匹配 [英] ValueError time data 'Fri Mar 11 15:59:57 EST 2016' does not match format '%a %b %d %H:%M:%S %Z %Y'

查看:48
本文介绍了ValueError时间数据'2016年3月11日星期五15:59:57'与格式'%a%b%d%H:%M:%S%Z%Y'不匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用以下格式简单地从以下日期创建一个datetime对象:"Fri Mar 11 15:59:57 EST 2016",格式为:'%a%b%d%H:%M:%S%Z%Y'.

I am trying to simply create a datetime object from the following date: 'Fri Mar 11 15:59:57 EST 2016' using the format: '%a %b %d %H:%M:%S %Z %Y'.

这是代码.

from datetime import datetime
date = datetime.strptime('Fri Mar 11 15:59:57 EST 2016', '%a %b %d %H:%M:%S %Z %Y')

但是,这将导致ValueError,如下所示.

However, this results in a ValueError as shown below.

ValueError: time data 'Fri Mar 11 15:59:57 EST 2016' does not match format '%a %b %d %H:%M:%S %Z %Y'

也许我的格式字符串缺少明显的问题,但是我已经一遍又一遍地检查了它.任何帮助将不胜感激,谢谢.

Maybe I am missing something obviously wrong with my format string, but I have checked it over and over. Any help would be greatly appreciated, thanks.

编辑以反映评论/问题以获取更多信息:

Edit to reflect comments/questions for more information:

我正在使用的Python版本是2.7.6.

The Python version I'm using is 2.7.6.

在Ubuntu 14.04上使用'locale'命令,我得到了:

Using the 'locale' command on Ubuntu 14.04 I get this:

$ locale
LANG=en_US.UTF-8
LANGUAGE=
LC_CTYPE="en_US.UTF-8"
LC_NUMERIC="en_US.UTF-8"
LC_TIME="en_US.UTF-8"
LC_COLLATE="en_US.UTF-8"
LC_MONETARY="en_US.UTF-8"
LC_MESSAGES="en_US.UTF-8"
LC_PAPER="en_US.UTF-8"
LC_NAME="en_US.UTF-8"
LC_ADDRESS="en_US.UTF-8"
LC_TELEPHONE="en_US.UTF-8"
LC_MEASUREMENT="en_US.UTF-8"
LC_IDENTIFICATION="en_US.UTF-8"
LC_ALL=

推荐答案

对于%Z说明符, strptime 仅识别"UTC","GMT"以及 time.tzname中的任何内容.(因此是否识别"EST"将取决于您计算机的时区).这是问题22377 .

For the %Z specifier, strptime only recognises "UTC", "GMT" and whatever is in time.tzname (so whether it recognises "EST" will depend on the time zone of your computer). This is issue 22377.

请参阅:

时区缩写名称在Python中?

解析包含人类可读时区的时区的最佳选择仍然是使用第三方

The best option for parsing timezones that include a human-readable time zone is still to use the third-party python-dateutil library:

import dateutil
date = dateutil.parse('Fri Mar 11 15:59:57 EST 2016')

如果您无法安装python-dateutil,则可以删除时区并手动进行解析,例如使用字典查找.

If you cannot install python-dateutil, you could strip out the timezone and parse it manually e.g. using a dictionary lookup.

这篇关于ValueError时间数据'2016年3月11日星期五15:59:57'与格式'%a%b%d%H:%M:%S%Z%Y'不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆