Zohab Ali
Zohab Ali

Reputation: 9574

Format to save value in DurationField in Django

I am unable to find that how I can set value of Duration Field in AdminPanel

Lets say that I want to set that value to 1 year

So that latter I can get DurationField value and add it to datetime.datetime.now()

All I want to know is that in which format I 'll have to add value in Duration field from AdminPanel.

I know there is a method my_model.duration = datetime.timedelta(days=20, hours=10)

But in my case Admin 'll have to add value from Admin Panel!!! So Please take time to understand question before marking it as a duplicate question

Upvotes: 0

Views: 2658

Answers (1)

Vaibhav Vishal
Vaibhav Vishal

Reputation: 7108

For duration field you need to enter duration in format DD HH:MM:SS.uuuuuu where uuuuuu is microseconds. For for one year you need to enter 365 0 or '365 0:0:0.000000' or 365 0:0:0(there are other possible combinations too). Don't enter just 365 it will consider it 365 seconds and 0 days.

>>> parse_duration('365')
datetime.timedelta(0, 365)

Internally Django uses the function parse_duration (django.utils.dateparse.parse_duration) to convert string to datetime.timedelta.

If you are unsure about what actual timedelta will be saved when you enter something in duration field in admin panel, open your favorite code editor and check the value you intend to enter:

>>> from django.utils.dateparse import parse_duration
>>> parse_duration('365 0')
datetime.timedelta(365)
>>> parse_duration('1 1:12:45.8979')
datetime.timedelta(1, 4365, 897900)

Upvotes: 2

Related Questions