日期格式为日

时间:2017-12-13 01:57:58

标签: python date days

目前,我的数据框中有一个日期和时间列表(2017-12-13 01:05:44) 任何人都可以帮我在我的数据框中创建一个新列('Day'),其中包含与我的日期列对应的日期列表。

*可以忽略时间。

例如,输出:

Date, Day
2017-12-13 01:05:44, Wednesday  
2017-12-12 01:02:13, Tuesday
2017-12-11 01:00:55, Monday
2017-12-10 00:59:31, Sunday
2017-12-09 00:58:23, Saturday

enter image description here

1 个答案:

答案 0 :(得分:1)

如果您将日期作为字符串,那么您必须将它们转换为日期时间对象

df['Date'] = pd.to_datetime(df['Date'])

和平铺你可以使用Series.dt.weekday_name

df['Day'] = df['Date'].dt.weekday_name

请参阅:timeseries - time date componentspandas.to_datetime()

工作示例

import pandas as pd

data = [
    "2017-12-13 01:05:44",
    "2017-12-12 01:02:13",
    "2017-12-11 01:00:55",
    "2017-12-10 00:59:31",
    "2017-12-09 00:58:23",
]

# create dataframe
df = pd.DataFrame(data, columns=['Date'])

print('\ntype before:\n', df.dtypes)

# convert strings to datetime
df['Date'] = pd.to_datetime(df['Date'])

print('\ntype after:\n', df.dtypes)

# get weekday name
df['Day'] = df['Date'].dt.weekday_name

print(df)

结果:

type before:
 Date    object
dtype: object

type after:
 Date    datetime64[ns]
dtype: object
                 Date        Day
0 2017-12-13 01:05:44  Wednesday
1 2017-12-12 01:02:13    Tuesday
2 2017-12-11 01:00:55     Monday
3 2017-12-10 00:59:31     Sunday
4 2017-12-09 00:58:23   Saturday