【问题标题】:Date does not match format in python datetime.strptime日期与 python datetime.strptime 中的格式不匹配
【发布时间】:2015-02-24 00:57:45
【问题描述】:

如果 MINYEAR 可能为 1,为什么我在 Python datetime.strptime 中有错误?我的设置是 Mac OSX 10.10.2 Python 3.4。

from datetime import *
    def days_diff(date1, date2):
        c=datetime.strptime('.'.join(str(i) for i in date1),"%Y.%m.%d")
        d=datetime.strptime('.'.join(str(i) for i in date2),"%Y.%m.%d")
        return print(c,d)

    days_diff((1, 1, 1), (9999,12,31))

ValueError: time data '1.1.1' does not match format '%Y.%m.%d'

【问题讨论】:

    标签: python datetime python-3.x strptime python-datetime


    【解决方案1】:

    %Y 格式仅适用于使用 四位数字的年份:

    >>> datetime.strptime('0001.1.1', '%Y.%m.%d')
    datetime.datetime(1, 1, 1, 0, 0)
    

    您可以使用str.zfill() 填充您的“日期”字符串:

    c = datetime.strptime('.'.join(str(i) for i in date1).zfill(8), "%Y.%m.%d")
    d = datetime.strptime('.'.join(str(i) for i in date2).zfill(8), "%Y.%m.%d")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多