Home > Mobile >  Problem in conversion of time from datetime to datetime.time
Problem in conversion of time from datetime to datetime.time

Time:01-23

I have a list of datetime object (let say datetime_obj) Now I want only its time part .

datetime_obj[0] = 22-Jun-23 13:32:00

I'm trying this :

time = [datetime.datetime.strptime(str(i)[11:], '%H:%M:%S') for I in datetime_obj]

But when I am printing time it showing 01-Jan-1900 13:32:00

Basically it is attaching a random date. what should I do?

CodePudding user response:

You can directly call the ".strftime("%H:%M:%S")" method on your datetime object. This way you can avoid the list comprehension method you were using.

For example, the one-liner

print(datetime.datetime.now().strftime("%H:%M:%S"))

gives you the actual time printed in the format that you need from the datetime object datetime_obj=datetime.datetime.now()

If you need the values instead, you could access to the .hour, .minute and .second properties of datetime_obj.

  • Related