How to put timedelta in django model?

后端 未结 7 1385
情歌与酒
情歌与酒 2020-12-09 14:29

With inspectdb I was able to get a \"interval\" field from postgres into django. In Django, it was a TextField. The object that I retrieved was indeed a timedelta object!

7条回答
  •  无人及你
    2020-12-09 15:26

    You can trivially normalize a timedelta to a single floating-point number in days or seconds.

    Here's the "Normalize to Days" version.

    float(timedelta.days) + float(timedelta.seconds) / float(86400)
    

    You can trivially turn a floating-point number into a timedelta.

    >>> datetime.timedelta(2.5)
    datetime.timedelta(2, 43200)
    

    So, store your timedelta as a float.

    Here's the "Normalize to Seconds" version.

    timedelta.days*86400+timedelta.seconds
    

    Here's the reverse (using seconds)

    datetime.timedelta( someSeconds/86400 )
    

提交回复
热议问题