1

The format from api google calendar is like '2017-04-26T13:00:00+02:00'.

I tried to convert to datetime without success:

datetime.datetime.strptime('2017-04-26T13:00:00+02:00', '%Y-%m-%dT%H:%M:%S+%z')

Es error I get:

'ValueError: time data, '2017-04-26T13:00:00+02:00' does not match format '%Y-%m-%dT%H:%M:%S+%z'

How do I get this code to work?

luoluo
  • 5,353
  • 3
  • 30
  • 41
prometeu
  • 679
  • 1
  • 8
  • 23

3 Answers3

2

this is because strptime expects for the %z format a string that looks like: +0200 not +02:00, i.e.:

>>> datetime.datetime.strptime('2017-04-26T13:00:00+0200', '%Y-%m-%dT%H:%M:%S%z')
datetime.datetime(2017, 4, 26, 13, 0, tzinfo=datetime.timezone(datetime.timedelta(0, 7200)))

so depending on your context, either you modify the string to fit strptime() expectations, or you can use a higher level library to handle your dates. Like maya or pendulum, that offer very flexible facilities to handle format parsing and relative date management.

>>> import pendulum, maya # you need to pip install them
>>> pendulum.parse('2017-04-26T13:00:00+02:00')
<Pendulum [2017-04-26T13:00:00+02:00]>
>>> maya.parse('2017-04-26T13:00:00+02:00')
<MayaDT epoch=1493204400.0>
zmo
  • 24,463
  • 4
  • 54
  • 90
2

Take a look at dateutil, the parse function will help you out.

>>> from dateutil.parser import parse
>>> dt = parse('2017-04-26T13:00:00+02:00')
>>> dt
datetime.datetime(2017, 4, 26, 13, 0, tzinfo=tzoffset(None, 7200))
luoluo
  • 5,353
  • 3
  • 30
  • 41
2

You may want to take a look in the documentation for PyTZ and Arrow, tho external modules that add functionality related to date and time. For instance, with arrow, you can do it pretty easily like this:

import arrow

my_arrow_object = arrow.get('2017-04-26T13:00:00+02:00')
my_datetime_object = my_arrow_object.datetime

print(my_datetime_object)
print(type(my_datetime_object))

This code prints the obtained timestamp and the type of my_datetime_object object, which is a datetime.datetime:

2017-04-26 13:00:00+02:00
<class 'datetime.datetime'>

Arrow also allows to easily generate "humanized" time strings (like "an hour ago" ou "two months ago"), which can be handy.

Victor Domingos
  • 1,003
  • 1
  • 18
  • 40
  • Hi, @prometeu! If this or any answer has solved your question please consider [accepting it](https://meta.stackexchange.com/q/5234/179419) by clicking the check-mark. This indicates to the wider community that you've found a solution and gives some reputation to both the answerer and yourself. There is no obligation to do this. – Victor Domingos Oct 12 '18 at 10:01