简体   繁体   English

如何将整列转换为日期格式?

[英]How to convert this whole column into date format?

I tried this to remove the unwanted characters but it is not working我试过这个来删除不需要的字符,但它不起作用

实际数据

from datetime import datetime

dates = []

for i in data.Date:
    date_time_str = str(data.Date[i])
    date_time_str = date_time_str.replace("M ","")
    date1 = date_time_str.replace(".","")
    dates.append(date1)

print(dates)

Use pd.to_datetime and give a correct format string for your data ( 'M %m.%Y' ):使用pd.to_datetime并为您的数据提供正确的格式字符串( 'M %m.%Y' ):

import pandas as pd

data = pd.DataFrame( {"Code":[114, 115, 116, 117], 
                      "Date":["M 02.2017", "M 03.2018", "M 04.2019", "M 05.2020",]})

print(data)

# simply use the correct format string for your data here
data["asDate"] = pd.to_datetime(data["Date"], format = "M %m.%Y") 
print(data)

Output: Output:

   Code       Date
0   114  M 02.2017
1   115  M 03.2018
2   116  M 04.2019
3   117  M 05.2020

   Code       Date     asDate
0   114  M 02.2017 2017-02-01
1   115  M 03.2018 2018-03-01
2   116  M 04.2019 2019-04-01
3   117  M 05.2020 2020-05-01

To get just the dates as list use仅获取日期作为列表使用

dates_1 = list(data["asDate"]) # contains <class 'numpy.datetime64'> and
dates_2 = list(data["asDate"].values) # <class 'pandas._libs.tslibs.timestamps.Timestamp'>

Assuming your dates are always prefaced with 'M ' (meaning that the actual date starts at position 2 in the string):假设您的日期总是以'M '开头(意味着实际日期从字符串中的 position 2 开始):

df['date'] = df['date'].apply(lambda x: pd.to_datetime(x[2:], format = '%m.%Y'))

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

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