简体   繁体   中英

Aware iso 8061 to datetime Python

I have as input following string:

input = "20170620015620.222+0000"

To convert it to datetime , I can use something like this:

utc_format_regex = re.compile('(?P<year>\d{4})'
                                      '(?P<month>\d{2})'
                                      '(?P<day>\d{2})'
                                      '(?P<hour>\d{2})'
                                      '(?P<minute>\d{2})'
                                      '(?P<second>\d{2})'
                                      '\.'
                                      '(?P<milisecond>\d{3})'
                                      '(?P<tz>\+\d{4})')
year, month, day, hour, minute, second, milisecond, tz = utc_format_regex.match(value).groups()

Parsing this to datetime seems easy, except param tzinfo ( I don't know, how to use it properly). That code won't work just because of such error:

TypeError: tzinfo argument must be None or of a tzinfo subclass, not type 'unicode'

datetime(year=int(year), month=int(month), day=int(day), hour=int(hour), minute=int(minute), second=int(second),
                                     microsecond=int(milisecond) * 1000, tzinfo=tz)

Just use strptime :

import datetime
parsed = datetime.datetime.strptime(input, '%Y%m%d%H%M%S.%f%z')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM