【问题标题】:Parse hw_clock output in Python在 Python 中解析 hw_clock 输出
【发布时间】:2017-06-02 08:39:03
【问题描述】:

的输出

/sbin/hwclock --show --utc

看起来像

2017-06-01 16:04:47.029482+1:00

如何在 Python 中将此字符串解析为日期时间对象?

【问题讨论】:

    标签: python python-datetime


    【解决方案1】:

    只使用日期时间:

    import datetime
    
    s = "2017-06-01 16:04:47.029482+1:00"
    try:
        stamp, zone = s.rsplit('+', 1)
        sign = '+'
    except ValueError:
        stamp, zone = s.rsplit('-', 1)
        sign = '-'
    zone = int(zone.replace(':', ''))
    new_s = '%s%s%04d' % (stamp, sign, zone)
    
    print(new_s)
    dt = datetime.datetime.strptime(new_s, "%Y-%m-%d %H:%M:%S.%f%z")
    print(dt.__repr__())
    

    【讨论】:

      【解决方案2】:

      可以使用第三方库python-dateutil(pip install python-dateutil):

      >>> import dateutil.parser
      >>> dateutil.parser.parse('2017-06-01 16:04:47.029482+1:00')
      datetime.datetime(2017, 6, 1, 16, 4, 47, 29482, tzinfo=tzoffset(None, 3600))
      

      如果您不想使用第三方库:

      import datetime
      import re
      
      
      def parse_iso_timestamp(clock_string):
          # Handle offset < 10
          clock_string = re.sub(r'\+(\d):', r'+0\1', clock_string)
      
          # Handle offset > 10
          clock_string = re.sub(r'\+(\d\d):', r'+\1', clock_string)
      
          # Parse
          dt = datetime.datetime.strptime(clock_string, '%Y-%m-%d %H:%M:%S.%f%z')
      
          return dt
      
      
      print(parse_iso_timestamp('2017-06-01 16:04:47.029482+1:00').__repr__())
      print(parse_iso_timestamp('2017-06-01 16:04:47.029482+10:00').__repr__())
      

      哪些输出:

      datetime.datetime(2017, 6, 1, 16, 4, 47, 29482, tzinfo=datetime.timezone(datetime.timedelta(0, 3600)))
      datetime.datetime(2017, 6, 1, 16, 4, 47, 29482, tzinfo=datetime.timezone(datetime.timedelta(0, 36000)))
      

      【讨论】:

      • 我不怕依赖。如果一个库让我的生活更轻松,我会在 setup.py 中扩展 install_requires 列表 :-) 谢谢你的回答。
      【解决方案3】:

      您可以使用datetime.strptime().将字符串解析为日期时间对象,它将日期字符串和格式作为输入并返回日期时间对象方法。

      【讨论】:

        【解决方案4】:

        按空间拳头值拆分为日期,如 2017-06-01

        d =date.split(" ")[0]

        按点分割以获取时间 t = data.split(" ")[1].split(".")[0]

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-05-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-06-29
          • 2021-11-01
          • 1970-01-01
          • 2015-04-26
          相关资源
          最近更新 更多