-7

I've seen solutions for converting something like '7:30 PM' using the datetime.strptime format '%I:%M%p' (e.g. here), but I have strings that look like this:

'05:15:00.000000000 AM'

The fact that there are both seconds and AM/PM seems to be uncommon.

How can I convert this?

Community
  • 1
  • 1
user3591836
  • 953
  • 2
  • 16
  • 29

2 Answers2

0

You can use parser from dateutil package to convert string into a datetime object, then use datetime object to get string from it.

from dateutil import parser
from datetime import datetime
dt = parser.parse("'24/NOV/18 05:15:00.000000000 AM'")
print(dt)
datetime_object = datetime.strftime(dt, '%b %d %Y %I:%M%p')
print(datetime_object)

Outputs:

2018-11-24 05:15:00 # parser output
Nov 24 2018 05:15AM # strftime output
Vineeth Sai
  • 3,389
  • 7
  • 23
  • 34
0

The main problem with your format is that Python does not support anything more granular than microseconds, as explained here. In fact, assuming you have 000 as the last three decimals of seconds, you can use the format below.

from datetime import datetime
datetime_object = datetime.strptime('24/NOV/18 05:15:00.000000000 AM', '%d/%b/%y %I:%M:%S.%f000 %p')

If you cannot make that assumption, this dirty hack should work:

from datetime import datetime
s = '24/NOV/18 05:15:00.000000000 AM'
s = s[:-9] + s[-6:]
datetime_object = datetime.strptime(s, '%d/%b/%y %I:%M:%S.%f %p')
marcotama
  • 1,991
  • 2
  • 19
  • 24