Reputation: 35
My Python code is showing an error in the date time format. What should be the correct format for this type of date: '09-Jul-11 12:00:00 AM'? The date is taken as a string from a text file. This is the code I used for date and time.
date=datetime.datetime.strptime(date, "%d-%B-%y %H:%M:%S %p")
This was the error I got.
ValueError: time data '09-Jul-11 12:00:00 AM' does not match format '%d-%B-%y %H:%M:%S %p'
P.S.: I am using Python 3.
Upvotes: 0
Views: 3254
Reputation: 2513
Online Demo
%b
should be used for abbreviated month name.You have used %B
which is used for full month name.
%H
is used for hour, using a 24-hour clock (00 to 23).%I
is used for hour, using a 12-hour clock (01 to 12)
import datetime
date = '09-Jul-11 12:00:00 AM'
date=datetime.datetime.strptime(date, "%d-%b-%y %I:%M:%S %p")
print(date)
Upvotes: 0
Reputation: 12927
The correct format string is: "%d-%b-%y %I:%M:%S %p"
(%b
for abbreviated month, %I
for 12-hours clock).
Upvotes: 0
Reputation: 3265
It's the wrong format for month and hour. Use %b
instead of %B
(month as locale's abbreviated name[1]) and %I
instead of %H
(12-hours format).
date=datetime.datetime.strptime(date, "%d-%b-%y %I:%M:%S %p")
[1]: thank to Ricky Han's comment
Upvotes: 1