Ahmed Nishaal
Ahmed Nishaal

Reputation: 96

How to convert str with microseconds completely to datetime.datetime

I'm trying to convert an str into datetime.datetime, and I want to do it with the microseconds intact. However the tutorials online don't show examples of carrying out the function with the microseconds, experimentations with the functions has turned out useless. Any help in solving this issue would be appreciated Hope the code below helps

now = datetime.now()  # 2021-11-03 03:12:14.470747 this is with microseconds
now = str(now)  # convert to str
time = datetime.strptime(time, "%m/%d/%Y %H:%M:%S.%f")  # NameError here

Upvotes: 0

Views: 38

Answers (1)

Tranbi
Tranbi

Reputation: 12711

First, your name error is due to a typo. time is undefined inside your parenthesis. Second your time format is not right (/ instead of -and year at the wrong position):

time = datetime.strptime(now, "%Y-%m-%d %H:%M:%S.%f") 

Upvotes: 1

Related Questions