3

I am getting below error while trying to do this

from datetime import datetime 

time1 = '2016-08-01 13:39:00+05:30'
x = datetime.strptime(time1, '%Y-%m-%d %H:%M:%S %z')
print(x)

Error is ...

ValueError: time data '2016-08-01 13:39:00+05:30' does not match format '%Y-%m-%d %H:%M:%S %z'
Sudheer1990
  • 397
  • 3
  • 14

3 Answers3

1

If you are using Python 2 or early versions of Python 3 (3.0 and 3.1), you can use the dateutil library for converting a string to a timezone aware object.

The code to do this is simple:

>>> import dateutil.parser
>>> dt = dateutil.parser.parse('2016-08-01 13:39:00+05:30')
>>> dt
datetime.datetime(2016, 8, 1, 13, 39, tzinfo=tzoffset(None, 19800))

If you are using Python 3.2 or later, the %z option has been added as a formatting option when parsing a date. You can accomplish this task without using dateutil in these versions by doing this:

>>> import datetime
>>> dt = datetime.datetime.strptime('2016-08-01 13:39:00+0530', "%Y-%m-%d %H:%M:%S%z")
>>> dt
datetime.datetime(2016, 8, 1, 13, 39, tzinfo=datetime.timezone(datetime.timedelta(0, 19800)))

Unfortunately, you do have to strip the colon (:) from the offset for this to work as expected.

Graham
  • 7,431
  • 18
  • 59
  • 84
Andy
  • 49,085
  • 60
  • 166
  • 233
0

this works in python 3.4, conforms to the datetime documentation

from datetime import datetime

time1 = '2016-08-01 13:39:00+0530'
x = datetime.strptime(time1, '%Y-%m-%d %H:%M:%S%z')
print(x)

gives

2016-08-01 13:39:00+05:30
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
0

Consider using dateparser:

>>> dateparser.parse('2016-08-01 13:39:00+05:30')
datetime.datetime(2016, 8, 1, 13, 39)
>>> dateparser.parse('2016-08-01 13:39:00+05:30', settings={'TO_TIMEZONE': 'UTC'})
datetime.datetime(2016, 8, 1, 8, 9)