0

I am receiving a json that prints time data '2016-04-15T02:19:17+00:00' I I cant seem to figure out the format of this unicode string.

I need to find a difference in time between then and now. The first step in that is to convert the string to structured format and Iam not able to find the format

fmt='"%Y-%m-%d %H:%M:%S %Z' 
#fmt='%Y-%m-%d %H:%M:%S.%f' 
print datetime.datetime.strptime(result_json['alert_time'], fmt)

I keep getting exception that it is not the same format

time data '2016-04-15T02:19:17+00:00' does not match format '"%Y-%m-%d %H:%M:%S %Z'
Victor
  • 427
  • 1
  • 6
  • 19

2 Answers2

1

There are a few problems with your format. First, it has a double quote " in it. Second, you need to include the T between the date and the time. Third, the timezone offset is not standard. Here is code that will work:

print datetime.datetime.strptime('2016-04-15T02:19:17', '%Y-%m-%dT%H:%M:%S')

If your alert_time is always in GMT, you can just trim the timezone off before calling strptime.

Brent Washburne
  • 12,904
  • 4
  • 60
  • 82
0

The answer by Brent is the safer and faster option rather than having things going on under the hood. But the amount of times I've had datetime as a frustrating bottleneck not associated with the main problem I wanted to test out, I will also point out that dateparser here has not yet been wrong for me and will take a huge range of inputs.

import dateparser
import datetime

date = '2016-04-15T02:19:17+00:00'

date_parser_format = dateparser.parse(date)
datetime_format = datetime.datetime.strptime('2016-04-15T02:19:17', '%Y-%m-%dT%H:%M:%S')

print date_parser_format
print datetime_format
roganjosh
  • 12,594
  • 4
  • 29
  • 46