How to strip date time in python
Solution 1
One line solution:
strDate ='Sun Jan 22 21:32:58 +0000 2012'
objDate = datetime.strptime(strDate, '%a %b %d %H:%M:%S +%f %Y')
print(objDate)
#2019-04-29 14:30:53
Details:
You just forgot to use %d
in order to capture the date number and the :
for the time and you ALSO need to capture +0000
.
Proof:
Solution 2
If your object is datetime.datetime
you can just simply do date()
from datetime import datetime
datetime1 = datetime.now()
date1 = datetime1.date()
Solution 3
I'm afraid that the currently accepted answer, by seralouk, is incorrect. Using "+%f" turns the numbers into fractions of seconds. It's fine for 0000, but will mess things up if they happen to be anything else.
This is because the "+0000" part is a time zone offset, and the proper way to parse it is by using the "%z" directive, which will handle the "+" sign as well, so remove that from the format string:
>>> date_string = "Sun Jan 22 21:32:58 +0000 2012"
>>> datetime.strptime(date_string, "%a %b %d %H:%M:%S %z %Y")
datetime.datetime(2012, 1, 22, 21, 32, 58, tzinfo=datetime.timezone.utc)
Related videos on Youtube
sr19 sr19
Updated on June 04, 2022Comments
-
sr19 sr19 almost 2 years
From a website I'm getting a date in such format:
Sun Jan 22 21:32:58 +0000 2012
. I understand that I must get rid of+0000
to convert it to the date, but how exactly I can do it? I read the documentation but my code is not working:from datetime import datetime strDate = 'Mon Apr 29 14:30:53 2019' objDate = datetime.strptime(strDate, '%a %b %H %M %S %Y')
I'm getting an error:
ValueError: time data 'Mon Apr 29 14:30:53 2019' does not match format '%d %m %H %M %S %Y'
And I don't really understand why. Or anyone knows how I can get a date from
Sun Jan 22 21:32:58 +0000 2012
?-
seralouk almost 5 yearsall you need is
objDate = datetime.strptime(strDate, '%a %b %d %H:%M:%S +%f %Y')
. See and accept my answer below
-
-
seralouk almost 5 yearsthis line is not useful:
new_strDate = strDate.replace(strDate.split(" ")[4] + " ", "")
. You can achieve the desired output using one line as I explained in my answer -
Ruben FV almost 5 yearsThank you, I just changed this.
-
seralouk almost 5 yearsNo. I mean that you do need it at all. See my answer to see how to achieve this without any
replace
orsplit
-
alkanen about 3 yearsWhat? "%f" is the microsecond fraction, the "+0000" is a time zone marker which is matched by "%z".
-
Cerin about 2 yearsOp obviously knows the difference between a date and datetime. They're asking how to easily remove the time component from a datetime.