haeram lee
haeram lee

Reputation: 23

how to get datetime to int in django? use datetime only hour and minute

I wanted to save the time as an int type so I could get the difference between the two times.

i import datetime and try to like this

now = datetime.now()

but i get this : 2017-11-18 05:47:35.262111

how to get only hour and minute to int

ex) 0547

I could not solve it.

Upvotes: 0

Views: 2965

Answers (3)

haeram lee
haeram lee

Reputation: 23

Thanks to you, I could solve it.

like this

hour = datetime.now().hour
minute = datetime.now().minute

if minute >10:
    return str(hour)+str(minute)
else:
    return str(hour)+"0"+str(minute)

Upvotes: 1

Satendra
Satendra

Reputation: 6865

You can use .time() and slice its hour and minute part.

str(datetime.now().time())[:5].replace(':','')
# OUTPUT: '0951'

An int doesn't have leading zeros, or any other formatting property. It is just a number. If you want to include a leading zero, I recommend using string.

Upvotes: 1

Gaurav Dhameeja
Gaurav Dhameeja

Reputation: 362

Use the hour and minute attributes and cast them to integer.

 import datetime
    hour_now = int(datetime.datetime.now().hour) # for hour
    minute_now = int(datetime.datetime.now().minute) # for minute

Upvotes: 2

Related Questions