I am trying to do a function like this:
def getDates(firstDate):
where firstDate is a string with this format:
"%Y-%m-%dT%H:%M:%SZ"
The function has to print on the screen the consecutive days with that date format, starting from the date of entry and the last one has to be the date when the function is executed.
This can be achieved using datetime and timedelta
from datetime import timedelta, datetime
def getDates(firstdate):
Convert the string to a datetime using strptime. And get the current datetime using now()
fdate=datetime.strptime(firstdate,"%Y-%m-%dT%H:%M:%SZ")
ldate=datetime.now()
To get the delta simply subtrack the last from the first, delta will be a timedelta so you can use timedelta.days to see the number of days to iterate through. if the delta is negative, the date is in the future. I assumed that his would return an empty list.
delta = ldate - fdate
alldates=[]
if delta.days>=0:
If the delta is 0 or more then create a list of datetime objects starting from lastdate, decrementing a day at a time.
alldates=list(map(lambda d: ldate-timedelta(days=d),range(delta.days+1)))
remember to reverse the list as this will start at the end date and work backwards to the start date alldates.reverse() return alldates
To test used current date -1 day, -1/2 day, +1/2 day and current(ish) time
print(getDates("2020-05-12T22:10:08Z"))
print(getDates("2020-05-12T12:10:08Z"))
print(getDates("2020-05-13T22:10:08Z"))
print(getDates("2020-05-13T12:10:08Z"))
[datetime.datetime(2020, 5, 13, 16, 7, 6, 883590)]
[datetime.datetime(2020, 5, 12, 16, 7, 6, 883747), datetime.datetime(2020, 5, 13, 16, 7, 6, 883747)]
[]
[datetime.datetime(2020, 5, 13, 16, 7, 6, 883907)]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.