Timestamp to Decimal day of year

14 views (last 30 days)
I have a dataset with a Timestamp column in the format (yyyy-mm-dd hour:minute:second.millisecond) (example: 2003-02-20 01:00:00.100) that I need to convert into decimal day of year, could I please get some guidance on how to do this?
thanks

Accepted Answer

Walter Roberson
Walter Roberson on 1 Dec 2020
d = datetime('2003-02-20 01:00:00.100')
d = datetime
20-Feb-2003 01:00:00
floor(days(d - dateshift(d, 'start', 'year'))) + 1
ans = 51
The +1 is because the start of year is day 1 of the year, and the subtraction gives the difference in days -- so Jan 2 would be 1 day difference, Jan 3 would be 2 days difference, and so on. Therefore to get day of year with Jan 1 being day 1, then you need to add 1.

More Answers (1)

Steven Lord
Steven Lord on 1 Dec 2020
dt = datetime('now', 'TimeZone', 'EST')
Warning: 'EST' specifies a time zone with a fixed offset from UTC, -05:00. This zone does not follow daylight saving time, and so may give unexpected results. See the datetime.TimeZone property for details about specifying time zones.
dt = datetime
30-Nov-2020 21:49:15
startOfYear = dateshift(dt, 'start', 'year')
startOfYear = datetime
01-Jan-2020
fractionOfYear = years(dt - startOfYear)
fractionOfYear = 0.9170
11/12
ans = 0.9167
Given that as I type this it's the evening of November 30th (roughly) 11/12th of the year has elapsed.
  6 Comments
Walter Roberson
Walter Roberson on 4 Dec 2020
The Answer that I posted computes decimal day number of the year. If the d variable were a vector of values, then the code I posted with floor() would compute the appropriate day number for each element of the array, basing each calculation upon the year appropriate to it. For example, the code would be perfectly happy to be fed dec 2 2020 and jan 2 2021 and would compute the day of the year relative to 2020 for the first and the day of the year relative to 2021 for the second.
Noelle Cielito Soriano
Noelle Cielito Soriano on 31 Dec 2020
Hello Steven and Walter, my apologies for replying so late. I wanted to let you know that I really appreciate the help you gave me with this question! Noelle

Sign in to comment.

Categories

Find more on Dates and Time in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!