Reputation: 169
def countdown_date(strdate):
datetimeobj = datetime.datetime.strptime(strdate, "%a, %b %d / %H:%M %p %Y")
return datetimeobj - datetime.datetime.today()
My above functions asks for strdate and it expects data similar to this
Sun, Dec 12 / 3:00 AM 2022
and the output will be a remaining count of days and hours til that date.
If the remaining days is a negative amount of days I'd like to increase the datetime object by one year and output the count
How do I do this?
Upvotes: 1
Views: 62
Reputation:
To check the days remaining on your timedelta
object, you can access the attribute days
.
def countdown_date(strdate):
datetimeobj = datetime.datetime.strptime(strdate, "%a, %b %d / %H:%M %p %Y")
delta = datetimeobj - datetime.datetime.today()
if delta.days < 0:
... # do your thing
return delta
Note here that delta
is of type datetime.timedelta
, and it ONLY holds days, seconds and microseconds. Hence, you can't increment the year value on it.
If you insist on incrementing a year on that timedelta
, you can just add 365 days to it ...
def countdown_date(strdate):
datetimeobj = datetime.datetime.strptime(strdate, "%a, %b %d / %H:%M %p %Y")
delta = datetimeobj - datetime.datetime.today()
if delta.days < 0:
return delta + datetime.timedelta(days=365)
return delta
Upvotes: 1