1

I'm trying to convert a string into a date format, to be later stored into an SQLite database. Below is the code line at which I'm getting an error.

date_object = datetime.strptime(date, '%b %d, %Y %H:%M %Z')

And this is the error:

File "00Basic.py", line 20, in spider
    date_object = datetime.strptime(date, '%b %d, %Y %H:%M %Z')   File "C:\Python27\lib\_strptime.py", line 332, in _strptime
    (data_string, format)) ValueError: time data 'Aug 19, 2016 08:13 IST' does not match format '%b %d, %Y %H %M %Z'

Question 1: How do I resolve this error?

Question 2: Is this the right approach for preparing to store the date in SQLite later?

Please Note: Very new to programming.

S Anwar
  • 53
  • 2
  • 7

2 Answers2

1

You could use pytz for the timezone conversion as shown:

from datetime import datetime
from pytz import timezone

s = "Aug 19, 2016 08:13 IST".replace('IST', '')
print(timezone('Asia/Calcutta').localize(datetime.strptime(s.rstrip(), '%b %d, %Y %H:%M')))
#2016-08-19 08:13:00+05:30
#<class 'datetime.datetime'>

I would suggest you to use dateutil incase you are handling multiple timezones of string.

Nickil Maveli
  • 29,155
  • 8
  • 82
  • 85
0

The problem is located in the %Z (Time zone) part of the format. As the documentation explains

%Z  Time zone name (empty string if the object is naive).   (empty), UTC, EST, CST

It looks like only UTC,EST and CST are valid. (Or it just doesn't recognize IST)

In order to fix this, you could use the %z parameter that accepts any UTC offset, like so:

struct_time = time.strptime("Aug 19, 2016 08:13 +0530", '%b %d, %Y %H:%M %z')

Update: Although this works fine in Python +3.2 it raises an exception when it's run with Python2

EndermanAPM
  • 327
  • 2
  • 22
  • thanks, but this hasn't worked. I'm getting the same error again. `ValueError: time data 'Aug 19, 2016 08:13 +530' does not match format '%b %d, %Y %H:%M %Z'` – S Anwar Aug 19 '16 at 09:00
  • Watch out, it's a **lowercase z**, also, the 0 (in +0530) is mandatory, the format of %z is HHMM – EndermanAPM Aug 19 '16 at 09:02
  • +z was giving me another error, `ValueError: 'z' is a bad directive in format '%b %d, %Y %H:%M %z'` – S Anwar Aug 19 '16 at 09:05
  • Oh, I'm sorry, as stated by [this answer](http://stackoverflow.com/a/2609335/4725649) looks like it doesn't work with python2. (And I was testing on python 3.5) – EndermanAPM Aug 19 '16 at 09:30