I want to convert day (say 88) and year (say 2004) into its constituent month and nearest number out of 2 possibilities:
If the day of month ranges from 1 to 14, then return 1, else return 15
I am doing this:
datetime.datetime(year, 1, 1) + datetime.timedelta(days - 1)
However, this is only part of the way to the soln. The end result for day 88 and year 2004 should be:
March 15 (Month is March and closest day is 15th march).
-- EDIT: Changed question to reflect that I mean day of year and not julian day
解决方案
You can use the replace method:
In [11]: d
Out[11]: datetime.datetime(2004, 3, 28, 0, 0)
In [12]: d.replace(day=1 if d.day < 15 else 15)
Out[12]: datetime.datetime(2004, 3, 15, 0, 0)
In [13]: t = pd.Timestamp(d)
In [14]: t.replace(day=1 if t.day < 15 else 15)
Out[14]: Timestamp('2004-03-15 00:00:00')
The reason this returns a new datetime rather than updating is because datetime objects are immutable (they are can't be updated).
Note: there's a format for that day of the month:
In [21]: datetime.datetime.strptime("2004+88", "%Y+%j")
Out[21]: datetime.datetime(2004, 3, 28, 0, 0)
In [22]: pd.to_datetime("2004+88", format="%Y+%j")
Out[22]: Timestamp('2004-03-28 00:00:00')