2

I get this date string format from the database and I need to convert it to datetime object in order to do subtraction.

'from': '2020-06-24T10:12:00.692+00:00'

I've tried this formatting, but that does not work.

"%Y-%m-%dT%H:%M:%S.%f%z"

Is that string even convertible in python?

Update: That's the strptime I run

datetime_obj1= datetime.strptime(row['from'], "%Y-%m-%dT%H:%M:%S.%f%z")

The error I get

ValueError                                Traceback (most recent call last)
<ipython-input-11-7798f7219c52> in <module>
     23 for row in list_of_events:
     24     print(row['id'])
---> 25     datetime_obj1= datetime.strptime(row['from'], "%Y-%m-%dT%H:%M:%S%z")
     26     print(datetime_obj1)
     27     #print(row['from']-row['to'])

/usr/lib/python3.6/_strptime.py in _strptime_datetime(cls, data_string, format)
    563     """Return a class cls instance based on the input string and the
    564     format string."""
--> 565     tt, fraction = _strptime(data_string, format)
    566     tzname, gmtoff = tt[-2:]
    567     args = tt[:6] + (fraction,)

/usr/lib/python3.6/_strptime.py in _strptime(data_string, format)
    360     if not found:
    361         raise ValueError("time data %r does not match format %r" %
--> 362                          (data_string, format))
    363     if len(data_string) != found.end():
    364         raise ValueError("unconverted data remains: %s" %

ValueError: time data '2020-06-24T10:12:00.692+00:00' does not match format '%Y-%m-%dT%H:%M:%S%z'
Asocia
  • 5,935
  • 2
  • 21
  • 46
Martynas
  • 309
  • 1
  • 2
  • 9
  • 2
    on Python 3.7+, use `datetime.fromisoformat('2020-06-24T10:12:00.692+00:00')` - by the way, your format code for `strptime` also works fine for me... – FObersteiner Jun 24 '20 at 10:43

3 Answers3

4

There is an issue about parsing RFC 3339 dates and times at here and it is resolved on python3.7.

So %z is not supported for < .

Asocia
  • 5,935
  • 2
  • 21
  • 46
  • nice, wasn't aware of that one yet... I wonder why the Z character can be parsed by `%z` in strptime but not `fromisoformat()`... (see also [here](https://stackoverflow.com/questions/127803/how-do-i-parse-an-iso-8601-formatted-date)) – FObersteiner Jun 24 '20 at 11:43
2

Without some actual code it's hard to say, where your mistake was.

The date format you suggested works just fine...

>>> from datetime import datetime
>>> datetime.strptime("2020-06-24T10:12:00.692+00:00", "%Y-%m-%dT%H:%M:%S.%f%z")
datetime.datetime(2020, 6, 24, 10, 12, 0, 692000, tzinfo=datetime.timezone.utc)
Sebastian Loehner
  • 1,302
  • 7
  • 5
1

on older Python versions, you should be able to make use of dateutil's parser:

from dateutil import parser

s = '2020-06-24T10:12:00.692+00:00'

dtobj = parser.isoparse(s)
# - or -
# dtobj = parser.parse(s)

# dtobj
# datetime.datetime(2020, 6, 24, 10, 12, 0, 692000, tzinfo=tzutc())
FObersteiner
  • 22,500
  • 8
  • 42
  • 72