Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the first and last second in python using datetime module

How to get the first and last second in python using datetime module which means 00:00:01 and 23:59:59.

I want to get the six datetime before today.

So, for example:

today 12/10, and I want to get

12/9 00:00:01 and 23:59:59

...

12/4 00:00:01 and 23:59:59

Thank you very much.

like image 734
Jimmy Lin Avatar asked Dec 01 '12 17:12

Jimmy Lin


1 Answers

Just use datetime.time.min and datetime.time.max:

>>> import datetime
>>> datetime.time.min
datetime.time(0, 0)
>>> datetime.time.max
datetime.time(23, 59, 59, 999999)

You can combine that with a datetime.date instance to get a full datetime.datetime instance:

>>> datetime.datetime.combine(datetime.date.today(), datetime.time.max)
datetime.datetime(2012, 12, 1, 23, 59, 59, 999999)

To re-use an existing datetime.datetime instance, use the .combine() method together with the .date() method on the datetime.datetime instance to create a new datetime.datetime instance:

>>> datetime.datetime.combine(datetime.datetime.now().date(), datetime.time.min)
datetime.datetime(2012, 12, 1, 0, 0)

To get a series of dates, use datetime.timedelta instances to create offsets. A series of dates relative to today is then easy:

today = datetime.date.today()
lastweek = today - datetime.timedelta(days=7)
for i in range(7):
    aday = lastweek + datetime.timedelta(days=i)
    first = datetime.datetime.combine(aday, datetime.time.min)
    last = datetime.datetime.combine(aday, datetime.time.max)
    print first, last
like image 123
Martijn Pieters Avatar answered Sep 21 '22 13:09

Martijn Pieters