2

In my project I have a string like this one:

"2018-03-07 06:46:02.737951"

I would like to get two variables: one in date format that contains the data, and the other for the time.

I tried:

from datetime import datetime
datetime_object = datetime.strptime('2018-03-07 06:46:02.737951', '%b %d %Y %I:%M%p')

but I get an error.

Then I tried:

from dateutil import parser
dt = parser.parse("2018-03-07 06:46:02.737951")

but I don't know what I can do with these results.

How can I extract the values for my vars "date_var" and "time_var"?

Keyur Potdar
  • 7,158
  • 6
  • 25
  • 40
Manuel Santi
  • 1,106
  • 17
  • 46
  • Possible duplicate of [Converting string into datetime](https://stackoverflow.com/questions/466345/converting-string-into-datetime) – Patrick Artner Mar 12 '18 at 15:52

2 Answers2

3
# Accessing the time as an object:
the_time = dt.time()
#the_time
datetime.time(23, 55)

# Accessing the time as a string:
the_time.strftime("%H:%M:%S")
'23:55:00'

Similar for Date

Refer here

Aditya
  • 2,380
  • 2
  • 14
  • 39
3

You need to match your string exactly. Reference: strftime-and-strptime-behavior

from datetime import datetime
dt = datetime.strptime('2018-03-07 06:46:02.737951', '%Y-%m-%d %H:%M:%S.%f')

print(dt.date())
print(dt.time())


d = dt.date() # extract date
t = dt.time() # extract time

print(type(d)) # printout the types
print(type(t))

Output:

2018-03-07
06:46:02.737951

<class 'datetime.date'>
<class 'datetime.time'>

Your format string is something along the lines of:

Month as locale’s abbreviated name.  
Day of the month as a zero-padded decimal number.
Year with century as a decimal number.
Hour (12-hour clock) as a zero-padded decimal number.
Minute as a zero-padded decimal number.
Locale’s equivalent of either AM or PM.

with some spaces and : in it - which does not match your format.

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69