问题描述
dt = datetime(2019,1,3,00,00) # 03/01/2019 00:00
dt_hour = dt.hour_of_year() # should be something like that
预期输出:dt_hour = 48
获得minutes_of_year
和seconds_of_year
解决方法
您可以使用timedelta
:
import datetime
dt = datetime.datetime(2019,1,3,00,00)
dt2 = datetime.datetime(2019,00)
print((dt-dt2).days*24)
输出:
48
,
一种自己实现的方法是:
def hour_of_year(dt):
beginning_of_year = datetime.datetime(dt.year,tzinfo=dt.tzinfo)
return (dt - beginning_of_year).total_seconds() // 3600
这首先创建一个新的datetime对象,该对象代表年初。然后,我们计算从年初开始的时间(以秒为单位),除以3600,然后取整数部分,以获得自年初以来已经过去的完整小时数。
请注意,使用days
对象的timedelta
属性将仅返回自年初以来的整天数。
这三个函数都在重用其代码。
import datetime
def minutes_of_year(dt):
return seconds_of_year(dt) // 60
def hours_of_year(dt):
return minutes_of_year(dt) // 60
def seconds_of_year(dt):
dt0 = datetime.datetime(dt.year,tzinfo=dt.tzinfo)
delta = dt-dt0
return int(delta.total_seconds())
经过编辑以考虑到可能的时区信息。
或者:子类化datetime,以便在以后的项目中更轻松地重用:
import datetime
class MyDateTime(datetime.datetime):
def __new__(cls,*args,**kwargs):
return datetime.datetime.__new__(cls,**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,tzinfo=self.tzinfo)
delta = self-dt0
return int(delta.total_seconds())
# create and use like a normal datetime object
dt = MyDateTime.now()
# properties and functions of datetime still available,of course.
print(dt.day)
# ... and new methods:
print(dt.hours_of_year())
,
您可以编写自定义函数
def get_time_of_year(dt,type = 'hours_of_year'):
intitial_date = datetime(dt.year,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