【问题标题】:Strptime - text format contains written month namesStrptime - 文本格式包含书面月份名称
【发布时间】:2015-07-29 11:26:51
【问题描述】:

是否可以将strptime 与如下文本一起使用:Wed 29th Jul 13:02:30。关键是我希望有适当的格式来比较日期。

所以我正在寻找类似的东西:

datetime.strptime(' '.join(date.split(' ')[1:]), "%d-%m-%h:%m:%s")

有可能吗?如果没有,最好的选择是什么?

【问题讨论】:

标签: python date datetime calendar strptime


【解决方案1】:

去掉日期上的“th”、“st”和“nd”。

然后使用:

datetime.strptime("Wed 29 Jul 13:02:30", "%a %d %b %H:%M:%S") 

【讨论】:

  • 我想使用 string.replace 或 re library。
  • 这大约是问题的 90%,OP 可以阅读文档以获取格式说明符,这是评论而不是答案
【解决方案2】:

使用re删除任何rd、nd、st和th然后正常解析:

s = "Wed 29th Jul 13:02:30"

from datetime import datetime
import  re
dte = datetime.strptime(re.sub("rd|nd|st|th","",s), "%a %d %b %H:%M:%S")

您也可以使用dateutil 为您完成工作:

 s= "Wed 29th Jul 13:02:30"
 from dateutil import parser

 print(parser.parse(s))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-23
    • 1970-01-01
    • 2017-02-19
    相关资源
    最近更新 更多