在python中将每年的日期转换为月份和两周 [英] In python convert day of year to month and fortnight

查看:516
本文介绍了在python中将每年的日期转换为月份和两周的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将日期(例如88)和年份(例如2004)转换为其组成月份和2种可能性中最接近的数字:

I want to convert day (say 88) and year (say 2004) into its constituent month and nearest number out of 2 possibilities:

如果是月中的某天范围从1到14,然后返回1,否则返回15

If the day of month ranges from 1 to 14, then return 1, else return 15

我正在这样做:

datetime.datetime(year, 1, 1) + datetime.timedelta(days - 1)

但是,这只是解决问题的方法的一部分。第88天和2004年的最终结果应该是:

However, this is only part of the way to the soln. The end result for day 88 and year 2004 should be:

3月15日(月份为3月,最接近的日期为3月15日)。

March 15 (Month is March and closest day is 15th march).

-编辑:更改问题以反映我的意思是一年中的一天而不是儒略日

-- Changed question to reflect that I mean day of year and not julian day

推荐答案

您可以使用替换方法:

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

这篇关于在python中将每年的日期转换为月份和两周的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆