Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: the end of the day using 24hr clock for datetime module [duplicate]

I'm using datetime module. I was told that 24:00:00 is a ValueError cause the hour is range from 00 to 23. So what time is the end of the day in 24hr clock?

---------Edited----------

Up to now I prefer Gord's answer. Though Igor has a very practical one.

My question is what's the very last time of datetime module. Since it has a resolution of microseconds. Gord's answer is the most accurate.

like image 689
spacegoing Avatar asked Jan 04 '16 14:01

spacegoing


3 Answers

datetime objects have a resolution of microseconds, so the last possible time value for a given day would be 23:59:59.999999. That is

hours: 23
minutes: 59
seconds: 59
microseconds: 999999

So, if you have a datetime, you can set it to the end of the day using the replace method:

import datetime

now_datetime = datetime.datetime.now()
end_of_day_datetime = now_datetime.replace(hour=23, minute=59, second=59, microsecond=999999)
like image 182
Gord Thompson Avatar answered Sep 22 '22 07:09

Gord Thompson


Get the beginning of the next day and substract 1 microsecond:

import datetime

source_datetime = datetime.datetime.now()
eod = datetime.datetime(
    year=source_datetime.year,
    month=source_datetime.month,
    day=source_datetime.day
) + datetime.timedelta(days=1, microseconds=-1)

print(eod)  # 2016-01-04 23:59:59.999999
like image 43
Igor Pomaranskiy Avatar answered Sep 18 '22 07:09

Igor Pomaranskiy


There is no 24:00:00 in practice. After 23:59:59 there is 0:00:00

like image 24
frlan Avatar answered Sep 18 '22 07:09

frlan