python多种格式日期转换-可识别年月类型(例如:200812)
应用场景 :读取csv文件,字符串转换为日期
1、日期格式为 年月,例如:200812
from datetime import datetime
import pandas as pd
df = pd.read_csv(r"E:\py\Project\测试数据\1001.csv")
df['年月'] = df['年月'].apply(lambda x: datetime.strptime(str(x), '%Y%m').date())
print(df['年月'])
2、日期格式为 年月日,例如:20081201
方法一:
最好用
from datetime import datetime
import pandas as pd
df = pd.read_csv(r"E:\py\Project\测试数据\1001.csv")
# 方法一:
df['年月'] = df['年月'].apply(lambda x: datetime.strptime(str(x), '%Y%m%d').date())
print(df['年月'])
方法二:
from datetime import datetime
import pandas as pd
df = pd.read_csv(r"E:\py\Project\测试数据\1001.csv")
# 方法二:
df['年月'] = df['年月'].apply(lambda x: datetime.datetime.fromtimestamp(x))
print(df['年月'])
方法三:
from datetime import datetime
import pandas as pd