【问题标题】:Python datetime formatting conversionPython日期时间格式转换
【发布时间】:2012-03-27 10:15:51
【问题描述】:

如果我有一个日期时间对象,比如 -

2012-03-10

如何将其转换为以下字符串格式-

Sat, 10 Mar 2012 00:00:00 EDT

【问题讨论】:

    标签: python datetime timezone


    【解决方案1】:
    datetime.strptime("2012-03-10", "%Y-%m-%d").strftime("%a, %d %b %Y %H:%M:%S EDT")
    

    很抱歉添加时区的原始方式。请参阅this question 了解更好的方法。

    【讨论】:

      【解决方案2】:
      >>> from datetime import datetime as dt
      >>> a = dt.now().replace(tzinfo = pytz.timezone('US/Eastern'))
      >>> a.strftime('%a, %d %b %Y %H:%M:%S %Z')
      'Fri, 09 Mar 2012 20:02:51 EST'
      

      【讨论】:

        【解决方案3】:

        Python 3.7+,使用dateutil:

        from datetime import datetime
        from dateutil import tz
        
        s = '2012-03-10'
        dt = datetime.fromisoformat(s).replace(tzinfo=tz.gettz('US/Eastern'))
        print(dt.strftime('%a, %d %b %Y %H:%M:%S %Z'))
        >>> 'Sat, 10 Mar 2012 00:00:00 EST'
        

        Python 3.9+,使用zoneinfo

        from datetime import datetime
        from zoneinfo import ZoneInfo
        
        s = '2012-03-10'
        dt = datetime.fromisoformat(s).replace(tzinfo=ZoneInfo('US/Eastern'))
        

        【讨论】:

          猜你喜欢
          • 2021-02-18
          • 1970-01-01
          • 2011-08-20
          • 1970-01-01
          • 1970-01-01
          • 2011-01-23
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多