【问题标题】:Parsing dates with multiple formats解析多种格式的日期
【发布时间】:2020-09-14 12:41:43
【问题描述】:

imaplib 返回的日期格式如下:

  dates = [
  'Mon, 27 May 2019 13:13:02 -0300 (ART)',
  'Tue, 28 May 2019 00:28:31 +0800 (CST)',
  'Mon, 27 May 2019 18:32:13 +0200',
  'Mon, 27 May 2019 18:43:13 +0200',
  'Mon, 27 May 2019 19:00:11 +0200',
  '27 May 2019 18:54:58 +0100',
  '27 May 2019 18:56:02 +0100',
  'Mon, 03 Jun 2019 10:19:56 GMT',
  '4 Jun 2019 07:46:30 +0100',
  'Mon, 03 Jun 2019 18:48:01 +0200',
  '5 Jun 2019 10:39:19 +0100'
]

如何将这些转换为 BST 日期时间?

这是我迄今为止尝试过的:

def date_parse(date):
  try:
    return datetime.strptime(date, '%a, %d %b %Y %H:%M:%S %z')
  except ValueError:
    try:
      return datetime.strptime(date[:-6], '%a, %d %b %Y %H:%M:%S %z')
    except ValueError:
      try:
        return datetime.strptime(date[:-6], '%d %b %Y %H:%M:%S')
      except ValueError:
        return datetime.strptime(date[:-4], '%a, %d %b %Y %H:%M:%S')

for date in dates:
    print(date)
    parsed_date = date_parse(date)
    print(parsed_date, type(parsed_date))
    print('')

但是我得到重复的日期,然后是 Traceback (most recent call last): 错误。

清理这些日期的最佳方法是什么? 是否有一个imaplib/email 函数可以让我们自动返回干净的日期?

【问题讨论】:

    标签: python python-3.x imaplib


    【解决方案1】:

    来自dateutil.parser 的parse 函数成功了:

    from dateutil.parser import parse
    
    dates = [
      'Mon, 27 May 2019 13:13:02 -0300 (ART)',
      'Tue, 28 May 2019 00:28:31 +0800 (CST)',
      'Mon, 27 May 2019 18:32:13 +0200',
      'Mon, 27 May 2019 18:43:13 +0200',
      'Mon, 27 May 2019 19:00:11 +0200',
      '27 May 2019 18:54:58 +0100',
      '27 May 2019 18:56:02 +0100',
      'Mon, 03 Jun 2019 10:19:56 GMT',
      '4 Jun 2019 07:46:30 +0100',
      'Mon, 03 Jun 2019 18:48:01 +0200',
      '5 Jun 2019 10:39:19 +0100'
    ]
    
    for date in dates:
        print(date, type(date))
        print(parse(date), type(parse(date)))
        print('')
    

    【讨论】:

      猜你喜欢
      • 2013-01-09
      • 2020-07-04
      • 1970-01-01
      • 2018-02-07
      • 1970-01-01
      • 2018-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多