Find decimal year from time

Hi,

I’ve searched for something in libraries like Dates and AstroTime, but maybe missed it as I’m surprised not to find it.
I would like to find the decimal time from a date, hour, minute, second, e.g.:
DateTime(2018,1,2,9,53,1) would give 2018.003828474404

This would be the reverse function from this thread:

Also, I need to take the leap second into account.

Aside from getting the year, which is in Dates module, getting the partial year can be done as follows (note the endless trickiness with dates requires care not to make bugs):

modyear(d) = 
  (d - firstdayofyear(d)) / (lastdayofyear(d)+Day(1) - firstdayofyear(d))

With this function:

julia> d = DateTime(2025,3,2,10,30,10)
2025-03-02T10:30:10

julia> year(d)
2025

julia> modyear(d)
0.16558250887874176

julia> year(d)+modyear(d)
2025.1655825088787
4 Likes

The yeardecimal function from DateFormats goes in both direction, DateTime ↔ decimal:

julia> using DateFormats

julia> dt = DateTime(2018,1,2,9,53,1)
2018-01-02T09:53:01

julia> yeardecimal(dt)
2018.003867992136

julia> yr = 2018.003867992136

julia> yeardecimal(yr)
2018-01-02T09:53:01
7 Likes

Yay thanks !
I’ll check if the leap second is managed.

Looks like that the leap second is not managed by this package.
E.g. a leap second was added the 2005/12/31; but:

dt = DateTime(2005,12,31,23,59,60)
ERROR: ArgumentError: Second: 60 out of range (0:59)

I think leap seconds are just not supported by Julia’s DateTimes. Probably on purpose? But idk.
There can be some packages that add leap seconds support to Julia.

1 Like

Link to an older thread with a detailed discussion of this topic.

Thanks everyone !