【问题标题】:How to get the datetime from a string containing '2nd' for the date in Python?python - 如何从包含'2nd'的字符串中获取日期时间?
【发布时间】:2023-03-18 12:25:01
【问题描述】:

我有几个字符串,我想从中获取日期时间。它们的格式如下:

Thu 2nd May 2013 19:00

我几乎知道如何将其转换为日期时间,除了我在使用“2nd”时遇到问题。我现在有以下内容

>>> datetime.strptime('Thu 02 May 2013 19:00', '%a %d %B %Y %H:%M')
datetime.datetime(2013, 5, 2, 19, 0)

使用零填充数字可以正常工作,但是当我尝试 2nd 时,它会给出 ValueError:

>>> datetime.strptime('Thu 2nd May 2013 19:00', '%a %d %B %Y %H:%M')
Traceback (most recent call last):
  File "<input>", line 1, in <module>
    (data_string, format))
ValueError: time data 'Thu 2nd May 2013 19:00' does not match format '%a %d %B %Y %H:%M'

the list of datetime directives 中,我找不到与日期的有序值(第 1、第 2、第 3 等)相关的任何内容。有人知道我怎样才能让它工作吗?欢迎所有提示!

【问题讨论】:

  • 试试:datetime.strptime('Thu 2nd May 2013 19:00', '%a %dnd %B %Y %H:%M')
  • @GrijeshChauhan OP 提到了多个字符串,如果日期是 3rd 怎么办?
  • @Ffisegydd 是的,你是对的,我的意思是你发布的就是答案。

标签: python string datetime


【解决方案1】:

考虑使用dateutil.parser.parse

它是一个第三方库,具有强大的解析器,可以处理这些事情。

from dateutil.parser import parse

s = 'Thu 2nd May 2013 19:00'

d = parse(s)
print(d, type(d))
# 2013-05-02 19:00:00 <class 'datetime.datetime'>

一个简短的警告(在您的情况下并没有真正发生):如果dateutil 无法在字符串中找到您的日期的某个方面(比如您遗漏了月份),那么它将默认为default争论。这默认为时间为 00:00:00 的当前日期。如果需要,您显然可以使用不同的 datetime 对象覆盖它。

安装dateutil 的最简单方法可能是使用pip 和命令pip install python-dateutil

【讨论】:

  • OP 的输入是“Thu 2nd May 2013 19:00”而不是“Thu 02 May 2013 19:00”
  • 顺便说一下,正如你所说,它是一个第三方库,所以,对于像我这样的 Python 初学者,你能告诉我们如何将它安装到 Python 中吗?
  • @sємsєм - 只需执行sudo pip install python-dateutil。如果您没有安装 pip,请在此处阅读:pip.pypa.io/en/latest/installing.html
【解决方案2】:

您可以预先解析原始字符串以调整日期以适合您的strptime,例如:

from datetime import datetime
import re

s = 'Thu 2nd May 2013 19:00'
amended = re.sub('\d+(st|nd|rd|th)', lambda m: m.group()[:-2].zfill(2), s)
# Thu 02 May 2013 19:00
dt = datetime.strptime(amended, '%a %d %B %Y %H:%M')
# 2013-05-02 19:00:00

【讨论】:

    【解决方案3】:
    import re
    from datetime import datetime
    def proc_date(x):
        return re.sub(r"\b([0123]?[0-9])(st|th|nd|rd)\b",r"\1",x)
    
    >>> x='Thu 2nd May 2013 19:00'
    >>> proc_date(x)
    'Thu 2 May 2013 19:00'
    >>> datetime.strptime(proc_date(x), '%a %d %B %Y %H:%M')
    datetime.datetime(2013, 5, 2, 19, 0)
    

    【讨论】:

      【解决方案4】:

      无需使用正则表达式或外部库即可直接从日期中删除后缀。

      def remove_date_suffix(s):
          parts = s.split()
          parts[1] = parts[1].strip("stndrh") # remove 'st', 'nd', 'rd', ...
          return " ".join(parts)
      

      那么就像使用strptime 一样简单:

      >>> s = "Thu 2nd May 2013 19:00"
      >>> remove_date_suffix(s)
      'Thu 2 May 2013 19:00'
      >>> datetime.strptime(remove_date_suffix(s), '%a %d %B %Y %H:%M')
      datetime.datetime(2013, 5, 2, 19, 0)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-04-01
        • 1970-01-01
        • 2021-10-07
        • 2016-05-13
        相关资源
        最近更新 更多