Answer the question
In order to leave comments, you need to log in
How to convert datetime in django?
I need a countdown timer on the site. The format should be: n months left j days hours:minutes:seconds. I figured out how to get the required date, but the problem is that it comes to timedelta() in the format: n days, hours:minutes:seconds. How can I convert this format to a convenient one for me or get individual values from timedelta.
What I get now:
What I would like to get:
My code:
from datetime import datetime
now = datetime.now()
date_left = datetime(2019, 12, 25) - now
formatedDate = date_left
Answer the question
In order to leave comments, you need to log in
pip install python-dateutil
>>> from datetime import datetime, timedelta
>>> from dateutil import relativedelta
>>> d1 = datetime.now()
>>> d2 = d1 + timedelta(days=285, hours=14, minutes=32, seconds=19)
>>> r = relativedelta.relativedelta(d2, d1)
>>> r.years, r.months, r.days, r.hours, r.minutes, r.seconds
(0, 9, 10, 14, 32, 19)
>>> from datetime import datetime, timedelta
>>> from dateutil import relativedelta
>>> r = relativedelta.relativedelta(datetime(2019, 12, 25), datetime.now())
>>> f'{r.months} мес {r.days} дн {r.hours:02}:{r.minutes:02}:{r.seconds:02}'
'9 мес 10 дн 04:32:01'
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question