简体   繁体   English

熊猫date_range和闰年

[英]Pandas date_range and leap years

When running this code: 运行此代码时:

a = pd.date_range("1959-12-09 00:00:00", "2013-12-09 12:00:00", freq = "365D6H")
weekDays = [dt.datetime.weekday(d) for d in a]
df = pd.DataFrame({"Date": a, "Jour": weekDays})
df.head(6)

I'm getting: 我越来越:

0 1959-12-09 00:00:00     2
1 1960-12-08 06:00:00     3   * 
2 1961-12-08 12:00:00     4
3 1962-12-08 18:00:00     5
4 1963-12-09 00:00:00     0
5 1964-12-08 06:00:00     1   *
6 1965-12-08 12:00:00     2

and so problems with leap years. 闰年问题。 How could I do to have exactly one calendar year between dates in spite of leap years ? 尽管有闰年,我怎么能在日期之间只有一个日历年呢?

Rather than use date_range , you could create this using a list comprehension: 您可以使用列表date_range来创建它,而不是使用date_range

In [11]: pd.to_datetime(["%s-12-09 %s:00:00" % (y, (6 * h) % 24)
                             for h, y in enumerate(xrange(1959, 2014))])
Out[11]: 
<class 'pandas.tseries.index.DatetimeIndex'>
[1959-12-09 00:00:00, ..., 2013-12-09 12:00:00]
Length: 55, Freq: None, Timezone: None

The frequency is None, since this isn't a regular frequency... if you try and add a numpy year and a numpy hour you'll see: 频率为无,因为这不是常规频率...如果您尝试添加一个numpy年和一个numpy小时,您将看到:

In [21]: np.timedelta64(1, 'Y') + np.timedelta64(6, 'h')
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-21-6a7f3e5b3315> in <module>()
----> 1 np.timedelta64(1, 'Y') + np.timedelta64(6, 'h')

TypeError: Cannot get a common metadata divisor for NumPy datetime metadata [Y] and [h] because they have incompatible nonlinear base time units

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM