简体   繁体   中英

Data set recognizes 12:00AM as 00:00AM

I am receiving the following error from Python:

ValueError: time data '05/10/2015 00:19:49 AM' does not match format '%d/%m/%Y %I:%M:%S %p'

I believe that the reason for this is that the data set is slightly inconsistent with the way the datetime library recognizes the 12 midnight time. I think it probably needs to be rectified by changing the 00 to 12 instead.

For example, the following data is displayed as follows:

05/10/2015 12:59:12 PM

The data is not using a 24 hour clock. Does anyone have a way of resolving this?

How about a simple try - except , trying %I first and using %H if you get a ValueError :

date_string = '05/10/2015 00:19:49 AM'
try:
    date = time.strptime(date_string, '%d/%m/%Y %I:%M:%S %p')
except ValueError:
    date = time.strptime(date_string, '%d/%m/%Y %H:%M:%S %p')

print(time.strftime('%d/%m/%Y %H:%M:%S %p', date))

Output:

05/10/2015 00:19:49 AM

The %I should work for all dates in 12-hour format except those with 00 for the hour. For these cases the 24-hour format using %H should work fine.

Works the same with datetime :

import datetime

date_string = '05/10/2015 00:19:49 AM'
try:
    date = datetime.datetime.strptime(date_string, '%d/%m/%Y %I:%M:%S %p')
except ValueError:
    date = datetime.datetime.strptime(date_string, '%d/%m/%Y %H:%M:%S %p')

print(date.strftime('%d/%m/%Y %H:%M:%S %p'))

Output:

05/10/2015 00:19:49 AM

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM