【问题标题】:How to convert date with suffix to another format in python如何在python中将带后缀的日期转换为另一种格式
【发布时间】:2014-10-26 06:35:19
【问题描述】:

我需要转换类似的东西:

Mar 31st, 2014
Aug 13th, 2014
Sep 2nd, 2014

进入:

31/03/2014
13/08/2014
2/09/2014

我一直在查看 strptime,但后缀碍事。 谢谢。

【问题讨论】:

    标签: python date converter


    【解决方案1】:

    你可以使用dateutil模块:

    >>> from dateutil.parser import parse
    >>> s = 'Mar 31st, 2014'
    >>> parse(s)
    datetime.datetime(2014, 3, 31, 0, 0)
    

    【讨论】:

    • 谢谢!! a = parse(date) 发布 = a.day.__str__()+"/"+a.month.__str__()+"/"+a.year.__str__()
    • 您的月份不会是零领先的,正如您在所需的示例输出中所示。此外,您明确使用私有方法 (__str__) 也是一个不好的迹象。请改用'{0.day}{0:/%m/%Y}'.format(a)
    • 为什么在这种特定情况下不好?
    【解决方案2】:

    您可以定义自己的函数来执行此操作:

    d = {'Jan': '01', 'Feb': '02', 'Mar': '03', 'Apr': '04', 'May': '05', 'Jun': '06', 'Jul': '07', 'Aug': '08', 'Sep': '09', 'Oct': '10', 'Nov': '11', 'Dec': '12'}
    
    
    def parser(date):
        date = date.split()    # date = ['Mar', '31st,', '2014']
        for i, elem in enumerate(date):
            if i == 0:
                month = d[elem]    # month = '03'
            elif i == 1:
                date = elem[:len(elem) - 3]    # date = '31'
            else:
                year = elem    # year = '2014'
        return date + "/" + month + "/" + year    # '31/03/2014'
    
    print parser('Mar 31st, 2014')
    

    这将返回31/03/2014

    【讨论】:

      【解决方案3】:

      使用标准 python 模块的主要问题是没有后缀(我的意思是'st'、'nd'、'th'..)的日期格式选项,并且没有前导零的日期没有选项。 至于后缀,您可以安全地删除它们,因为它们不会出现在月份名称中。至于没有前导零的日期,我们可以通过显式选择日期部分来构造字符串。

      from datetime import datetime 
      
      def convert(dt_string, in_format='%b %d, %Y', out_format='{0.day}{0:/%m/%Y}'):
          for suffix in ('st', 'nd', 'rd', 'th'):
              dt_string = dt_string.replace(suffix, '')
          return out_format.format(datetime.strptime(dt_string, in_format))
      
      
      dates = ['Mar 31st, 2014', 'Aug 13th, 2014', 'Sep 2nd, 2014']
      print map(convert, dates)
      

      【讨论】:

        【解决方案4】:

        我会使用下面的方法。

        import datetime
        import re
        
        # Collect all dates into a list.
        dates = [ 'Mar 31st, 2014', 'Aug 13th, 2014', 'Sep 2nd, 2014' ]
        
        # Compile a pattern to replace alpha digits in date to empty string.
        pattern = re.compile('(st|nd|rd|th|,)')
        
        # Itegrate through the list and replace the old format to the new one.
        for offset, date in enumerate(dates):
            date = pattern.sub('', date)
            date = datetime.datetime.strptime(date, '%b %d %Y')
            dates[offset] = str(date.day) + '/' + str(date.month) + '/' + str(date.year)
            print(dates[offset]);
        

        【讨论】:

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