2

I am using datetime to convert a time string. I used the reference for the specifying the format. How should I have coded the format?

In [19]:import datetime In [20]: d Out[20]: 'Oct. 30, 2014, 6:17 a.m.' In [21]: format Out[21]: '%b. %d, %Y, %I:%M%p.' In [22]: date_object = datetime.datetime.strptime(d, format) --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-22-78ccb659d6ac> in <module>() ----> 1 date_object = datetime.datetime.strptime(d, format) /usr/lib/python2.7/_strptime.pyc in _strptime(data_string, format) 323 if not found: 324 raise ValueError("time data %r does not match format %r" % --> 325 (data_string, format)) 326 if len(data_string) != found.end(): 327 raise ValueError("unconverted data remains: %s" % ValueError: time data 'Oct. 30, 2014, 6:17 a.m.' does not match format '%b. %d, %Y, %I:%M%p.' 

I came across this tool, "dateutil" and

In [20]: d Out[20]: 'Oct. 30, 2014, 6:17 a.m.' In [34]: from dateutil import parser In [35]: date_obj = parser.parse(d) In [36]: date_obj Out[36]: datetime.datetime(2014, 10, 30, 6, 17) 

I get this

/home/tilaprimera/.virtualenvs/picovico/lib/python2.7/site-packages/django/db/models/fields/__init__.py:1278: RuntimeWarning: DateTimeField GCMDevice.created_at received a naive datetime (2014-10-30 06:17:00) while time zone support is active. RuntimeWarning) 

The thing is, I am trying to query the database with this time but unfortunately, with some information lost, I do not get a match on the time.

2
  • please add the language tag Commented Jan 15, 2015 at 6:28
  • I guess the problem is what it says your string "does not match format" your provided. Please double check it. Commented Jan 15, 2015 at 6:36

2 Answers 2

3

Close, but no cigar. I figured it out by doing datetime.datetime.now().strftime() with your format string and playing around a bit. You need two changes:

d = 'Oct. 30, 2014, 6:17 AM' format = '%b. %d, %Y, %I:%M %p' 

There is unfortunately no format specifier that accepts a.m. (at least not in the English locale I tried). For more on this, see here: https://stackoverflow.com/a/2925280/4323

Sign up to request clarification or add additional context in comments.

2 Comments

So I will need to change the "a.m." to AM and then proceed?
That would be one way, yes.
1

Since 'a.m.' is non standard you could substitute it using the re module. Also, you do not have a space in your format string after the minute position.

import datetime import re d='Oct. 30, 2014, 6:17 a.m.' format='%b. %d, %Y, %I:%M %p' d = re.sub('([pa])\.m\.',r'\1m',d) date_object = datetime.datetime.strptime(re.sub('([pa])\.m\.',r'\1m',d),format) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.