-
一只萌萌小番薯
自己实现的一种方法是:def hour_of_year(dt):
beginning_of_year = datetime.datetime(dt.year, 1, 1, tzinfo=dt.tzinfo)
return (dt - beginning_of_year).total_seconds() // 3600这首先创建一个新的 datetime 对象来表示年初。然后我们计算自年初以来的时间(以秒为单位),除以 3600 并取整数部分以获得自年初以来经过的完整小时数。请注意,使用对象days的属性timedelta将仅返回自年初以来的完整天数。
-
哈士奇WWW
您可以使用timedelta:import datetimedt = datetime.datetime(2019, 1, 3, 00, 00, 00)dt2 = datetime.datetime(2019, 1, 1, 00, 00, 00)print((dt-dt2).days*24)输出:48
-
qq_遁去的一_1
所有三个函数,重用它们的代码。import datetimedef minutes_of_year(dt): return seconds_of_year(dt) // 60def hours_of_year(dt): return minutes_of_year(dt) // 60def seconds_of_year(dt): dt0 = datetime.datetime(dt.year, 1, 1, tzinfo=dt.tzinfo) delta = dt-dt0 return int(delta.total_seconds())编辑以考虑可能的时区信息。或者:子类 datetime,以便在以后的项目中更容易重用:import datetimeclass MyDateTime(datetime.datetime): def __new__(cls, *args, **kwargs): return datetime.datetime.__new__(cls, *args, **kwargs) def minutes_of_year(self): return self.seconds_of_year() // 60 def hours_of_year(self): return self.minutes_of_year() // 60 def seconds_of_year(self): dt0 = datetime.datetime(self.year, 1, 1, tzinfo=self.tzinfo) delta = self-dt0 return int(delta.total_seconds())# create and use like a normal datetime objectdt = MyDateTime.now()# properties and functions of datetime still available, of course.print(dt.day)# ... and new methods:print(dt.hours_of_year())
-
跃然一笑
我有一个数据框 DF,它的“时间戳”列的类型为 datetime64[ns]。列时间戳如下所示:DF['Timestamp']:0 2022-01-01 00:00:001 2022-01-01 01:00:002 2022-01-01 02:00:003 2022-01-01 03:00:004 2022-01-01 04:00:00... 8755 2022-12-31 19:00:008756 2022-12-31 20:00:008757 2022-12-31 21:00:008758 2022-12-31 22:00:008759 2022-12-31 23:00:00Name: Timestamp, Length: 8760, dtype: datetime64[ns]我以这种方式提取“一年中的小时”:DF['Year'] = DF['Timestamp'].astype('M8[Y]')DF['DayOfYear'] = (DF['Timestamp'] - DF['Year']).astype('timedelta64[D]')DF['Hour'] = DF['Timestamp'].dt.hour + 1 DF['HourOfYear'] = DF['DayOfYear'] * 24 + DF['Hour']首先,它从时间戳中提取年份。接下来,它根据天数(换句话说,一年中的某一天)创建从年初到该时间戳的时间增量。然后它从时间戳中提取小时。最后,它使用该公式计算一年中的小时。最后看起来像这样:DF: Timestamp ... HourOfYear0 2022-01-01 00:00:00 ... 1.01 2022-01-01 01:00:00 ... 2.02 2022-01-01 02:00:00 ... 3.03 2022-01-01 03:00:00 ... 4.04 2022-01-01 04:00:00 ... 5.0... 8755 2022-12-31 19:00:00 ... 8756.08756 2022-12-31 20:00:00 ... 8757.08757 2022-12-31 21:00:00 ... 8758.08758 2022-12-31 22:00:00 ... 8759.08759 2022-12-31 23:00:00 ... 8760.0[8760 rows x 6columns]
-
繁星点点滴滴
你可以写一个自定义函数def get_time_of_year(dt, type = 'hours_of_year'): intitial_date = datetime(dt.year, 1,1, 00, 00, 00) duration = dt - intitial_date days, seconds = duration.days, duration.seconds hours = days * 24 + seconds // 3600 minutes = (seconds % 3600) // 60 if type == 'hours_of_year': return hours if type == 'days_of_year': return days if type == 'seconds_of_year': return seconds if type == 'minuts_of_year': return minutes测试功能get_time_of_year(dt, 'hours_of_year')#>>48