2

I have the follwoing format for my date 2014-02-23T18:42:26.000009. I want to extract the date, so I have used the following code:

from datetime import datetime
date_object = datetime.strptime('2014-02-23T18:42:26.000009', '%Y-%m-%d')

However, I got the following error message:

Traceback (most recent call last):
File "C:/Users/d774911/PycharmProjects/GlobalData/Test2.py", line 4, in <module>
date_object = datetime.strptime('2014-02-23T18:42:26.000009', '%Y-%m-%d')
File "C:\Python34\lib\_strptime.py", line 500, in _strptime_datetime
tt, fraction = _strptime(data_string, format)
File "C:\Python34\lib\_strptime.py", line 340, in _strptime
data_string[found.end():])
ValueError: unconverted data remains: T18:42:26.000009

Any ideas?

2
  • 1
    That looks like ISO 8601 format. If that's the case, see this previous question: stackoverflow.com/questions/127803/… Commented Apr 23, 2015 at 7:09
  • Oh, and also: it's not "striptime", it's strptime, from the compound of string parse time. The Python function is named after the POSIX function of the same name. (See man 3 strptime for details.) Commented Apr 23, 2015 at 7:14

2 Answers 2

5

You need to add the remains of your string to date format.So replace '%Y-%m-%d' with with '%Y-%m-%dT18:42:26.000009' :

>>> date_object = datetime.strptime('2014-02-23T18:42:26.000009', '%Y-%m-%dT18:42:26.000009')
>>> date_object
datetime.datetime(2014, 2, 23, 0, 0)

Or as a more general way you can use dateutil.parser :

>>> from dateutil.parser import parse
>>> parse('2014-02-23T18:42:26.000009', fuzzy=True)
datetime.datetime(2014, 2, 23, 18, 42, 26, 9)

And if you just want the date :

>>> parse('2014-02-23T18:42:26.000009', fuzzy=True).date()
datetime.date(2014, 2, 23)
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the prompt reply. I have many records (more than 600,000 records) and won't be able to match them using the same value above. Ideas?
@user3089324 Welcome. in that case you can use some date parsers like dateutil
@user3089324 checkout the edit!
wonderful solution!!!
0
import re
time="2014-02-23T18:42:26.000009"
print re.sub('T.*','',time)

output: 2014-02-23

Further you can use the strip('-') to return a list containing ['2014', '02', '23']

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.