Reputation: 443
I have been using a function to convert datetime objects to decimal years based on this post python how to convert datetime dates to decimal years but I was unable to find any post showing the inverse: decimal years to datetime objects. Any help in this regard is appreciated.
thanks,
Upvotes: 7
Views: 8990
Reputation: 29
I found defining a 'base' and calculating down to the second level was unnecssary as the same accuracy seems to be preserved just by using days. I believe this response is less verbose.
datetime(int(x), 1, 1) + timedelta(days = (x % 1) * 365)
The above 365 can easily be replaced with @PaulMcGuire's recommendation, adapted for days.
Upvotes: 1
Reputation: 142226
Not properly tested, but looks about right:
from datetime import datetime, timedelta
start = 2012.5
year = int(start)
rem = start - year
base = datetime(year, 1, 1)
result = base + timedelta(seconds=(base.replace(year=base.year + 1) - base).total_seconds() * rem)
# 2012-07-02 00:00:00
Upvotes: 10
Reputation: 32449
What I would do is the following:
Split the decimal year into its integer and fractional part.
Create a datetime object for the 1st of January of the year = integer of decimal year.
Convert the fractional part to seconds.
Add a timedelta(seconds=...) to the datetime object.
Upvotes: 0