代码之家  ›  专栏  ›  技术社区  ›  Harshit Singh

使用Python将数字集转换为日期格式

  •  1
  • Harshit Singh  · 技术社区  · 7 年前

    我有一个名为“train”的数据帧,其列ID以一种非常不寻常的方式表示“date”。例如,ID中的某些条目:

    For example, the value of ID 2013043002 represents the date 30/04/2013 
    02:00:00
    

    前4位代表年份,后2位分别代表月份和日期。最后两位代表时间。

    4 回复  |  直到 7 年前
        1
  •  3
  •   jezrael    7 年前

    使用 to_datetime 带参数 format -检查 http://strftime.org/

    df = pd.DataFrame({'ID':[2013043002,2013043002]})
    
    df['ID'] = pd.to_datetime(df['ID'], format='%Y%m%d%H')
    print(df)
                       ID
    0 2013-04-30 02:00:00
    1 2013-04-30 02:00:00
    
    print(df['ID'].dtype)
    datetime64[ns]
    
        2
  •  2
  •   Arunesh Singh    7 年前

    使用 datetime 用于日期时间操作。

    datetime.strptime(d,"%Y%m%d%H").strftime("%d/%m/%Y %H:%M:%S")
    
        3
  •  0
  •   Nestor Colt    7 年前

    首先,如果你想在Id中始终使用相同的输入样式,你可以使用字符串或数字格式。。。

    Id = 2013043002 
    Year = Id[0:3] 
    Month = Id[4:5] 
    Day = Id[6:7] 
    Time= Id[-2:-1]  
    
    DateFormat = "{}-{}-{}".format(Day,Month,Year)
    TimeFormar = "%d:00:00"%Time 
    Print (DateFormat) 
    Output:
    04:30:2013 
    

    然后,您可以将其包装到一个函数中,通过循环传递每个ID,并管理您的数据。

    当然,如果您不知道以前的ID输入格式,您应该使用其他时间模块选项,并管理字符串格式以按您想要的顺序显示。

        4
  •  0
  •   Örlog    7 年前

    通过使用模块datetime,您可以使用函数strtime轻松实现这一点:

    my_date = datetime.datetime.strptime(ID, "%Y%m%d%H")
    

    %Y%m%d%H” 是日期的格式:%Y是年,%m是月(0填充),%d是日(0填充),%H是小时(24小时,0填充)。看见 http://strftime.org/ 更多信息。