0

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)
SiHa
  • 7,830
  • 13
  • 34
  • 43
User007
  • 295
  • 4
  • 11

1 Answers1

1

Just use strptime:

import datetime
parsed = datetime.datetime.strptime(input, '%Y%m%d%H%M%S.%f%z')
Błotosmętek
  • 12,717
  • 19
  • 29
  • 1
    A warning for python 2 users: `%f` may or may not be supported, depending on your OS and interpreter. – Aran-Fey Jun 22 '17 at 09:39
  • %z isn't supported under my version (or server version). Cannot do that, this is 2.7 Python – User007 Jun 22 '17 at 10:09
  • Here you have, why %z isn't working. https://stackoverflow.com/questions/20194496/iso-to-datetime-object-z-is-a-bad-directive?rq=1 – User007 Jun 22 '17 at 10:11
  • Tough luck, you probably need `pytz` module then. – Błotosmętek Jun 22 '17 at 10:19
  • Seems, you can do smth like: 'tz = int(tz[1:])/1000*3600' 'datetime(year=int(year), month=int(month), day=int(day), hour=int(hour), minute=int(minute), second=int(second), microsecond=int(milisecond) * 1000, tzinfo=dateutil.tz.tzoffset(None,tz))' I do not know, what happens negative values though... Should it be negative number? – User007 Jun 22 '17 at 10:22
  • one mistake here, should be: int(tz[1:])/100*3600 btw. Can you answer using pytz? I do not know conception. I'd be glad :) – User007 Jun 22 '17 at 10:32