gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 14:36:29 24 4
gpt4 key购买 nike

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

ValueError: Invalid format string

问题是什么?

最佳答案

相同的代码在 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) 的精彩回答

In the Python source for datetime and time, the string STRFTIME_FORMAT_CODES tells us:

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

So now if we man strftime (on BSD systems such as Mac OS X), you'll find support for %s:

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

你能做什么?

看来您需要 Unix 时间戳。正如@jleahy here建议的那样,

If you want to convert a python datetime to seconds since epoch you should do it explicitly:

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

In Python 3.3+ you can use timestamp() instead:

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

关于python - 如何使用 Lib 'dateutil' 转换日期字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46902029/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com