【问题标题】:How to convert date string by using Lib 'dateutil'?如何使用 Lib 'dateutil' 转换日期字符串?
【发布时间】:2017-10-24 04:08:15
【问题描述】:

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

ValueError: 无效的格式字符串

有什么问题?

【问题讨论】:

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


    【解决方案1】:

    相同的代码在 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." 
    

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

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

    你能做什么?

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

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

    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
    

    【讨论】:

    • 所以它似乎在 Python 3.5 中行不通。我只是不知道出了什么问题。
    • 根据this post,您的选项%s 不存在。我不明白为什么它对我有用,它会打印 Unix 时间戳。这是一个我应该问的好问题。无论如何,请检查可用选项here
    • 非常有见地!让我看看。
    【解决方案2】:

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

    如果您查看this page,您会看到评论:

    平台特定指令:支持的全套格式代码因平台而异,因为 Python 调用平台 C 库的 strftime() 函数,平台变化很常见。

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

    另一个跨平台不兼容的例子:Windows 不能识别格式字符串中的连字符,但它可以在 linux 上工作。例如:

    print(time.strftime("%-I:%M %p")) #这在windows上失败

    如果您坚持使用此处提到的与平台无关的格式化字符串选项,这可能最适合您的代码:http://strftime.org/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-07-06
      • 2020-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-09
      相关资源
      最近更新 更多