Convert a decimal day of the year to a timestamp

£可爱£侵袭症+ 提交于 2019-12-13 08:59:31

问题


How can I convert a decimal representation of a day in the year to a timestamp with all the parts, both the full date and the time?

For example, my first decimal is 22.968530853511766 and I want it in a nice timestamp format.


回答1:


Use a timedelta() object with your value as the days parameter; add it to midnight December 31st of the previous year:

from datetime import datetime, timedelta

epoch = datetime(datetime.now().year - 1, 12, 31)
result = epoch + timedelta(days=your_decimal)

Demo:

>>> from datetime import datetime, timedelta
>>> epoch = datetime(datetime.now().year - 1, 12, 31)
>>> epoch + timedelta(days=22.968530853511766)
datetime.datetime(2015, 1, 22, 23, 14, 41, 65743)
>>> print(epoch + timedelta(days=22.968530853511766))
2015-01-22 23:14:41.065743

A datetime object can be formatted any number of ways with the datetime.strftime() method; I relied on the default str() conversion as called by print() in the demo.



来源:https://stackoverflow.com/questions/30490352/convert-a-decimal-day-of-the-year-to-a-timestamp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!