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?

Mazdak
  • 105,000
  • 18
  • 159
  • 188
  • 1
    That looks like ISO 8601 format. If that's the case, see this previous question: http://stackoverflow.com/questions/127803/how-to-parse-iso-formatted-date-in-python – Daniel Pryden Apr 23 '15 at 07:09
  • Oh, and also: it's not "striptime", it's `strptime`, from the compound of `str`ing `p`arse `time`. The Python function is named after the POSIX function of the same name. (See `man 3 strptime` for details.) – Daniel Pryden Apr 23 '15 at 07:14

2 Answers2

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)
Mazdak
  • 105,000
  • 18
  • 159
  • 188
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']

V Sree Harissh
  • 665
  • 5
  • 24