12

I have:

test_date = "2017-07-20-10-30"

and then use:

day = datetime.strptime(test_date[11:], "%H-%M")

which gives me

1900-01-01 10:30:00

How do I just get: 10:30:00 as type datetime.time?

vvvvv
  • 25,404
  • 19
  • 49
  • 81
Mat.S
  • 1,814
  • 7
  • 24
  • 36
  • Possible duplicate of [Converting string into datetime](https://stackoverflow.com/questions/466345/converting-string-into-datetime) – fredtantini Jul 23 '17 at 08:02

2 Answers2

15

You can use the strftime method of the datetime object like this:

day.strftime('%H:%M')

More information here: https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior

Ok, I misunderstood. Use day.time() to get a time object.

Cory Madden
  • 5,026
  • 24
  • 37
3

you can parse your string using datetime.strptime to a datetime object and then call .time() on that to get the time:

from datetime import datetime

strg = "2017-07-20-10-30"

dt = datetime.strptime(strg, '%Y-%m-%d-%H-%M')
tme = dt.time()
print(tme)  # 10:30:00

the strftime() and strptime() Behavior is well documented.

of course you can also chain these calls:

tme = datetime.strptime(strg, '%Y-%m-%d-%H-%M').time()
hiro protagonist
  • 44,693
  • 14
  • 86
  • 111