Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to strip date time in python

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?

like image 924
sr19 sr19 Avatar asked Oct 26 '25 17:10

sr19 sr19


2 Answers

If your object is datetime.datetime you can just simply do date()

from datetime import datetime
datetime1 = datetime.now() 
date1 = datetime1.date()
like image 125
Gabriel Avatar answered Oct 29 '25 05:10

Gabriel


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)
like image 22
alkanen Avatar answered Oct 29 '25 07:10

alkanen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!