23

I've got this date time string:

post["date"] = "2007-07-18 10:03:19"

I'd like to extract just "2007-07-18" as a date. I've seen some reference to strptime but I'm not sure how to use it. How can I extract the date from this string?

0

7 Answers 7

59

The other two answers are fine, but if you actually want the date for something else, you can use the datetime module:

from datetime import datetime
d = datetime.strptime('2007-07-18 10:03:19', '%Y-%m-%d %H:%M:%S')
day_string = d.strftime('%Y-%m-%d')

It might be overkill for now, but it'll come in useful. You can see all of the format specifiers here.

2
  • can u plz tell me the format of "Wed Dec 17 14:58:39 IST 2014" ? Jan 31, 2015 at 7:22
  • @DinoopNair this should be the format you are looking for: "%a %b %d %H:%M:%S %Z %Y" Jul 16, 2015 at 20:03
8

In your case, just use split:

>>> d1="2007-07-18 10:03:19"
>>> d1.split()[0]
'2007-07-18'
>>> 

(The 1st part after splitting with whitespace)

If you insist on using strptime, the format is "%Y-%m-%d %H:%M:%S" :

>>> import time
>>> time.strptime(d1,"%Y-%m-%d %H:%M:%S")
time.struct_time(tm_year=2007, tm_mon=7, tm_mday=18, tm_hour=10, tm_min=3, tm_sec=19, tm_wday=2, tm_yday=199, tm_isdst=-1)
>>> time.strftime("%Y-%m-%d", _)
'2007-07-18'
>>> 
1
  • 2
    to avoid IndexError for empty data, you could use d1.partition(' ')[0]
    – jfs
    Dec 22, 2014 at 3:04
2

You can use https://pypi.python.org/pypi/python-dateutil which can support any datetime format e.g:

>>> from dateutil.parser import parse
>>> d1="2007-07-18 10:03:19"
>>> date_obj = parse(d1)
>>> date_obj
datetime.datetime(2007, 7, 18, 10, 3, 19)
>>> date_obj.strftime("%Y-%m-%d")
'2007-07-18'
>>> d2 = "18-07-2007 10:03:19"
>>> d = parse(d2)
>>> d
datetime.datetime(2007, 7, 18, 10, 3, 19)
>>> d.strftime("%Y-%m-%d")
'2007-07-18'
2

Probably not what you are looking for but you could just split the string:

post["date"].split()[0]

would give you '2007-07-18'

1

You can use the parsedatetime module.

>>> from parsedatetime.parsedatetime import Calendar
>>> c = Calendar()
>>> c.parse("2007-07-18 10:03:19")
((2008, 11, 19, 10, 3, 19, 2, 324, 0), 2)
1

You can use the mx.DateTime module from eGenix

import mx

date_object = mx.DateTime.Parser.DateTimeFromString('2007-07-18 10:03:19')
print "%s-%s-%s" % (date_object.year, date_object.month, date_object.day)

will output: 2007-07-18

1
import dateutil.parser
a = "2007-07-18 10:03:19"
d = dateutil.parser.parse(b).date()

Your Output will be like this **

datetime.date(2007, 07, 18)

**

Not the answer you're looking for? Browse other questions tagged or ask your own question.