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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With