繁体   English   中英

在 python 中将月-年格式更改为年-月-日格式

[英]change month-year format to year-month-date format in python

我有一个 CSV 文件作为输入,其中一列的日期格式为年月。 我需要将列格式更改为年-月-日格式,这意味着月末日期。 我正在使用 Python 3。此外,我还在聚合 function 中使用修改后的列,并按 function 分组。

例如:2020-01

2020-02

2020-03

2020-04

预期结果:

2020-01-31

2020-02-29(考虑闰年)

2020-03-31

2020-04-30

很快...

from calendar import monthrange
from datetime import date
def month_end(year, month):
    return date(year=year, month=month, day=monthrange(year, month)[1]).isoformat()
>>> month_end(2020, 2)
'2020-02-29'
import pandas as pd
import datetime as dt
import calendar as cal

# making data frame from csv file 
df = pd.read_csv("Table.csv")

# (month_year)->Column Name
df['month_last_dates'] = [datetime.datetime(date.year, date.month,
      calendar.monthrange(date.year, date.month)[1]) for date in month_year]

# defining aggregation process for each column
aggregations={ 'Metric':sum }

# Group by and aggregate                              
print( df.groupby(['col1', 'month_last_dates','col2']).agg(aggregations) )

暂无
暂无

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

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