python将日期转换为周_在python中将每年的日期转换为月份和两周

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')

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值