13

I have a field that shows time as 1900-01-01 00:05:00 but I want to show it as just 00:05:00 i.e. just five minutes.

I have been looking at the python documentation and it is driving me crazy. From the question How do I find the time difference between two datetime objects in python? it looks like is should be something do with timedelta but I am not getting any closer to a solution. The question Converting Date/Time to Just Time suggests you can just use a format tag but that is not working for me. I also looked at converting date time to string without success, I know this is something simple but I have looked at hundreds of pages looking for something simple. All help would be appreciated.

Community
  • 1
  • 1
Brett
  • 3,296
  • 5
  • 29
  • 45

2 Answers2

18

Say you have a Datetime object now:

now.time().strftime('%H:%M:%S')

satoru
  • 31,822
  • 31
  • 91
  • 141
14

Load the string with strptime() and get the time() component:

>>> from datetime import datetime
>>> s = "1900-01-01 00:05:00"
>>> dt = datetime.strptime(s, "%Y-%m-%d %H:%M:%S")
>>> dt.time().isoformat()
'00:05:00'

Here we are dumping the time with isoformat() in ISO 8601 format, but you can also dump the datetime.time back to string with strftime():

>>> dt.time().strftime("%H:%M:%S")
'00:05:00'
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195