I want to convert "07-JUL-22 08.54.22.153000000 AM" to a datetime object in python in order to be able to perform timedelta operations inside a pandas dataframe!
Your help is much appreciated.
CodePudding user response:
pd.to_datetime
can infer 07-JUL-22 08:54:22.153000000 AM
, you can do
df['date2'] = pd.to_datetime(
df['date'].str.replace(r'(\d{2})\.(\d{2})\.(\d{2})', r'\1:\2:\3', regex=True)
)
print(df)
date date2
0 07-JUL-22 08:54:22.153000000 AM 2022-07-07 08:54:22.153
CodePudding user response:
Nanoseconds are a bit of a problem for the batteries included with Python:
from datetime import datetime
d = "07-jul-22 08.54.22.153000 am"
dt = datetime.strptime(d, "%d-%b-%y %H.%M.%S.%f %p")
Note that the timestamp is truncated to microseconds. How important are those for your application?
You can truncate nanoseconds to microseconds with a regex:
import re
d = "07-jul-22 08.54.22.153000000 am"
d = re.sub(r"(\d\d\d\d\d\d)\d\d\d", r"\1", d)
(Cheat sheet: https://strftime.org/ )