How to strip date time in python

19,855

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:

enter image description here

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)
Share:
19,855

Related videos on Youtube

sr19 sr19
Author by

sr19 sr19

Updated on June 04, 2022

Comments

  • sr19 sr19
    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
      seralouk almost 5 years
      all you need is objDate = datetime.strptime(strDate, '%a %b %d %H:%M:%S +%f %Y') . See and accept my answer below
  • seralouk
    seralouk almost 5 years
    this 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
    Ruben FV almost 5 years
    Thank you, I just changed this.
  • seralouk
    seralouk almost 5 years
    No. I mean that you do need it at all. See my answer to see how to achieve this without any replace or split
  • alkanen
    alkanen about 3 years
    What? "%f" is the microsecond fraction, the "+0000" is a time zone marker which is matched by "%z".
  • Cerin
    Cerin about 2 years
    Op obviously knows the difference between a date and datetime. They're asking how to easily remove the time component from a datetime.