Search code examples
python-3.xpython-datetimestrptime

issue with datetime.strptime python


This is my code:

import datetime
t1 = "Fri 11 Feb 2078 00:05:21"
t2 = "Mon 29 Dec 2064 03:33:48"
t3 = "Sat 02 May 2015 19:54:36"
t3_time = datetime.datetime.strptime(t3,"%a %d %B %Y %H:%M:%S")

print("debug")

t2_time = datetime.datetime.strptime(t2,"%a %d %B %Y %H:%M:%S")
t1_time = datetime.datetime.strptime(t1,"%a %d %B %Y %H:%M:%S")

error: ValueError: time data 'Mon 29 Dec 2064 03:33:48' does not match format '%a %d %B %Y %H:%M:%S'

Why t3 is getting parsed properly whereas t1 and t2 not getting parsed properly?


Solution

  • You need to give the full name of the month in your input

    this should work

    import datetime
    
    t1 = "Fri 11 February 2078 00:05:21"
    t2 = "Mon 29 December 2064 03:33:48"
    t3 = "Sat 02 May 2015 19:54:36"   
    
    print("debug")
    
    t1_time = datetime.datetime.strptime(t1,"%a %d %B %Y %H:%M:%S")
    t2_time = datetime.datetime.strptime(t2,"%a %d %B %Y %H:%M:%S")
    t3_time = datetime.datetime.strptime(t3,"%a %d %B %Y %H:%M:%S")
    

    Or just use %b instead of %B

    import datetime
    
    t1 = "Fri 11 Feb 2078 00:05:21"
    t2 = "Mon 29 Dec 2064 03:33:48"
    t3 = "Sat 02 May 2015 19:54:36"   
    
    print("debug")
    
    t1_time = datetime.datetime.strptime(t1,"%a %d %b %Y %H:%M:%S")
    t2_time = datetime.datetime.strptime(t2,"%a %d %b %Y %H:%M:%S")
    t3_time = datetime.datetime.strptime(t3,"%a %d %b %Y %H:%M:%S")
    

    note that adding a textual day in your input won't change anything

    for example

    t4 = "Fri 02 May 2015 19:54:36"
    t4_time = datetime.datetime.strptime(t4,"%a %d %B %Y %H:%M:%S")
    print(t3_time == t4_time)
    

    should return True