Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a string with date and time to a date [duplicate]

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?

like image 626
Alex Avatar asked Nov 19 '08 10:11

Alex


People also ask

How do I convert a string to a date?

Using strptime() , date and time in string format can be converted to datetime type. The first parameter is the string and the second is the date time format specifier. One advantage of converting to date format is one can select the month or date or time individually.

How do you convert date and time to string in Python?

To convert Python datetime to string, use the strftime() function. The strftime() method is a built-in Python method that returns the string representing date and time using date, time, or datetime object.

Can we convert string to date in SQL?

In SQL Server, converting a string to date explicitly can be achieved using CONVERT(). CAST() and PARSE() functions.


3 Answers

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.

like image 122
babbageclunk Avatar answered Sep 21 '22 21:09

babbageclunk


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' >>>  
like image 21
gimel Avatar answered Sep 23 '22 21:09

gimel


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'
like image 39
PBD Avatar answered Sep 23 '22 21:09

PBD