views:

2161

answers:

5

I've got this:

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

And from post["date"], I'd like to extract just "2007-07-18". I've seen some reference to strptime without being sure how to use it

I'm not really familiar with python, just 1-2 scripts a year, so the solution might be obvious for a lot of you :)

+2  A: 

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'
>>>
gimel
+1  A: 

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

post["date"].split()[0] would give you '2007-07-18'

Ashy
+10  A: 

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.

wilberforce
A: 

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

Oli
A: 

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)