繁体   English   中英

如何在python中将时间转换为类别?

[英]How to Convert time to category in python?

如何将时间转换为某个类别?

例如,17:30:13 到 19:30:13 之间的时间应归类为“晚上”。 12:00:12 和 13:00:12 之间的时间应该属于“中午”。

在 python 中执行此操作的好方法是什么?

如果您想将它用于机器学习,您通常希望它是一个整数值,或者将其转换为单热编码。

要获得整数值,您可以对小时进行整数除法:

from datetime import datetime,timedelta

values = [datetime.now() + timedelta(hours=i) for i in range(24)] 

[value.hour // 6 for value in values]

产量:

[3, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3]

我没有使用任何机器学习库。 编写了一个函数,该函数根据一天中的下限小时返回一个类别。

根据您的示例,我假设下限时间确实优先考虑类别。 也许我想更好地理解用例。

# hour can be some number from 0 to 23 which is also the lower bound hour 
# in the mentioned interval 
# 17:30:13- 19:30:13 should fall under "evening"
# 12:00:12-13:00:12  should fall under "noon"
# For 17:30:13- 19:30:13 , hour will be 17
# For 12:00:12-13:00:12 , hour will be 12
get_category(hour):
    if hour < 12:
        return "morning"
    elif hour == 12:
        return "noon"
    elif hour > 12 and hour < 16:
        return "evening"
    else:
        return "night"

您可能需要自己命名一个函数并自定义截止时间。

import datetime
# test date
Testdate = datetime.datetime.now().time()

def GetDateCate (DateInput):
    # name a cutoff date:
    noon = datetime.time(12) 
    evening =datetime.time(18) 
    if Testdate <noon:
        print('Morning')
    elif Testdate <evening:
        print('Afternoon')
    else: 
        print('Night')

GetDateCate(Testdate)

暂无
暂无

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

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