hlkstuv_23900
hlkstuv_23900

Reputation: 882

Trying to convert to datetime

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.

Upvotes: 2

Views: 1737

Answers (2)

tharen
tharen

Reputation: 1300

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)

Upvotes: 1

John Zwinck
John Zwinck

Reputation: 249093

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

Upvotes: 3

Related Questions