在Python中解析hw_clock输出

gue*_*tli 2 python python-datetime

的输出

/sbin/hwclock --show --utc

好像

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

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

Pac*_* H. 5

您可以使用第三方库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))
Run Code Online (Sandbox Code Playgroud)

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

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__())
Run Code Online (Sandbox Code Playgroud)

哪个输出:

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)))
Run Code Online (Sandbox Code Playgroud)