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
?
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 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.
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.
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.
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With