Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert datetime to time in python

Tags:

python

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?

like image 649
Mat.S Avatar asked Jul 23 '17 07:07

Mat.S


People also ask

How do I convert datetime to time in Python?

In Python, there is no such type of datatype as DateTime, first, we have to create our data into DateTime format and then we will convert our DateTime data into time. A Python module is used to convert the data into DateTime format, but in the article, we will be using the datetime module to do this task.

How can I get time from datetime?

How to Get the Current Time with the datetime Module. To get the current time in particular, you can use the strftime() method and pass into it the string ”%H:%M:%S” representing hours, minutes, and seconds.

How do I convert datetime to seconds in Python?

To convert a datetime to seconds, subtracts the input datetime from the epoch time. For Python, the epoch time starts at 00:00:00 UTC on 1 January 1970. Subtraction gives you the timedelta object. Use the total_seconds() method of a timedelta object to get the number of seconds since the epoch.

How do I convert string to time in Python?

We can convert a string to datetime using strptime() function. This function is available in datetime and time modules to parse a string to datetime and time objects respectively.


2 Answers

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.

like image 193
Cory Madden Avatar answered Nov 11 '22 20:11

Cory Madden


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()
like image 23
hiro protagonist Avatar answered Nov 11 '22 20:11

hiro protagonist