0

Are there anyway of making a timefunction which returns time and not years? For example:

enter code here

def time(t):
    return datetime.datetime.strptime(t, "%H:%M")
print(time('6:00')) 

If I write this I will get: 1900-01-01 06:00:00, but I only want 06:00

Reza amin
  • 37
  • 6
  • 2
    Does this answer your question? [How to extract hours and minutes from a datetime.datetime object?](https://stackoverflow.com/questions/25754405/how-to-extract-hours-and-minutes-from-a-datetime-datetime-object) – lorenzozane Nov 16 '20 at 09:34
  • Why not just print the argument you're passing to the function? It seems to be what you need... – Tomerikoo Nov 16 '20 at 09:35
  • Because I need to use the function on different occasions thats why – Reza amin Nov 16 '20 at 09:40
  • I need a function not only use it for the print i showed – Reza amin Nov 16 '20 at 09:42

1 Answers1

0

You're creating a datetime object. You can format a datetime object with strftime

import datetime


def time(t):
    return datetime.datetime.strptime(t, "%H:%M")
    
print(f"{time('06:00').strftime('%H:%M')}")
Alexander Riedel
  • 1,329
  • 1
  • 7
  • 14
  • I see! Are there no way of returning it directly to the function so that I dont have to write .strftime('%H:%M') everytime? – Reza amin Nov 16 '20 at 09:44
  • I mean by editing the function to directly give out what you just wrote? – Reza amin Nov 16 '20 at 09:44
  • sure, but then it starts really not making any sense because your really return your input and not even a datetime object you could do other stuff with..`return datetime.datetime.strptime(t, "%H:%M").strftime('%H:%M')` – Alexander Riedel Nov 16 '20 at 09:47