Skip to content Skip to sidebar Skip to footer

What Is The Datetime Equivalent For Pandas Dayofyear?

I'm looking to get an array of values of day of year from a list of datetimes. I can get the week number, for example, using the method isocalendar. But what's the method for an in

Solution 1:

Try using strftime:

np.array([int(i.strftime("%j")) for i in datetimes])

However,

np.array([datetime.timetuple().tm_yday for datetime in datetimes])

works and is faster.

Solution 2:

Here is a short example of days between dates, using only the Python built-in datetime module:

importdatetimedates= [
    datetime.date(2019, 12, 30), datetime.date(2019, 12, 31),
    datetime.date(2020, 1, 1),   datetime.date(2020, 1, 2)
]

for d in dates:base_date=d.replace(month=1,day=1)days_between=(d-base_date)/datetime.timedelta(days=1)print(base_date,d,days_between)2019-01-01 2019-12-30 363.02019-01-01 2019-12-31 364.02020-01-01 2020-01-01 0.02020-01-01 2020-01-02 1.0

You would add 1 to days_between if you wanted 1-based indexing (Jan 1 is 'day zero' in this example).

This is based on the section 'Examples of Usage: date' here: https://docs.python.org/3/library/datetime.html

Post a Comment for "What Is The Datetime Equivalent For Pandas Dayofyear?"