如何使用Lib'dateutil'转换日期字符串?

时间:2017-10-24 04:08:16

标签: python python-3.x python-dateutil

在Python中运行dateutil.parser.parse("2017-09-19T04:31:43Z").strftime('%s')时,我收到以下错误:

  

ValueError:格式字符串无效

有什么问题?

2 个答案:

答案 0 :(得分:0)

相同的代码在Python 2中适用于我。

from dateutil.parser import parse
print(parse("2017-09-19T04:31:43Z").strftime('%s'))
# 1505813503

import dateutil.parser
print(dateutil.parser.parse("2017-09-19T04:31:43Z").strftime('%s'))
# 1505813503

OP声称这不起作用,给出了相同的ValueError: Invalid format string错误。

一种解释是,根据这篇文章,您的选项%s并不存在。请参阅valid options of time.strftime here

为什么%s可以在我的系统上运行?

来自this post

的Darren Stone的精彩回答
  

在日期时间和时间的Python源代码中,字符串STRFTIME_FORMAT_CODES告诉我们:

"Other codes may be available on your platform.
See documentation for the C library strftime function." 
     

所以现在如果我们使用strftime(在Mac OS X等BSD系统上),你会发现对%s的支持:

%s is replaced by the number of seconds since the Epoch, UTC (see mktime(3))." 

你能做什么?

似乎你想要Unix时间戳。正如@jleahy here所建议的那样,

  

如果你想将epthon日期时间转换为自纪元以来的秒数   应该明确地做:

datetime.datetime(2012,04,01,0,0).strftime('%s') # '1333234800'
(datetime.datetime(2012,04,01,0,0) - 
 datetime.datetime(1970,1,1)).total_seconds() # 1333238400.0 
     

在Python 3.3+中,您可以使用timestamp()代替:

datetime.datetime(2012,4,1,0,0).timestamp() # 1333234800.0

答案 1 :(得分:0)

可能是您只是输入错了。也许您打算使用大写的S,它提供秒的格式。如果不是这样,%s作为格式字符串可能是特定于平台的。

如果您查看this page,将会看到注释:

  

特定于平台的指令:由于平台调用C语言库的strftime()函数,并且平台版本很常见,因此支持的格式代码集在各个平台上都不同。

例如,在Windows上,strftime中根本不接受%s(小写)。 Windows将识别%S(大写),并将秒作为零填充的十进制数字。

另一个跨平台不兼容的示例:Windows在Linux上运行时无法识别格式字符串中的连字符。例如:

print(time.strftime(“%-I:%M%p”))#在Windows上失败

如果您坚持此处提到的与平台无关的格式设置字符串选项,那么可能是最好的代码:http://strftime.org/