简体   繁体   English

Python:如何写入CSV并将日期从DataFrame追加到文件名

[英]Python: How to write to CSV and append date from a DataFrame to the filename

I am using the following method to write to a csv file with the date appended to the filename. 我正在使用以下方法写入日期附加到文件名的csv文件。

outpath = r'C:\test'
filename = "filename_"+(time.strftime("%Y%m%d")+".csv")

df.to_csv(outpath + "\\" + filename)


print outpath + "\\" + filename

C:\test\filename_20140621.csv

But I have a problem when the routine crosses midnight and the date added is then incorrect. 但是当例程经过午夜并且添加的日期不正确时,我遇到了问题。

I have the correct date in a DataFrame df, like this: 我在DataFrame df中有正确的日期,如下所示:

df['Date/Time'].head()
Out[54]:

0   2014-06-20
1   2014-06-20
2   2014-06-20
3   2014-06-20
4   2014-06-20
Name: Date/Time, dtype: object

I would like to use this date in the filename, but I can't find the correct way to reference it 我想在文件名中使用此日期,但找不到正确的引用方式

For example, I put this date in a new dataframe named 'date' with just the one column: 例如,我将此日期放在只有一个列的名为“ date”的新数据框中:

date = pd.to_datetime(df['Date/Time'])
date.head()

Out[15]:

0   2014-06-20
1   2014-06-20
2   2014-06-20
3   2014-06-20
4   2014-06-20
Name: Date/Time, dtype: datetime64[ns]

and tried the following: 并尝试了以下方法:

filename = "filename_"+ date._slice(slice(1))+".csv") filename =“ filename _” + date._slice(slice(1))+“。csv”)

...and various similar things. ...以及各种类似的东西。

Can anybody show me how to set the filename to include the date from the DataFrame? 有人可以告诉我如何设置文件名以包括DataFrame中的日期吗?

Any help much appreciated. 任何帮助,不胜感激。

Give your date Series, you could take the first, or the least, as you prefer: 给定您的date系列,可以根据需要选择第一个或最少一个:

>>> date.head()
0   2014-06-20
1   2014-06-20
2   2014-06-20
3   2014-06-20
4   2014-06-20
Name: Date/Time, dtype: datetime64[ns]
>>> date.iloc[0].strftime("%Y%m%d")
'20140620'
>>> date.min().strftime("%Y%m%d")
'20140620'

.iloc[0] accesses the first row (regardless of whether its index is 0, as it is here, or 217123), and .min() scans them all and finds the smallest. .iloc[0]访问第一行(无论其索引是0还是此处的217123),. min .min()都将它们全部扫描并找到最小的行。 (If you know they're all the same, or that the one you want will be first, then .iloc[0] will be faster than .min() , of course, but maybe they're not sorted and you want the smallest.. or the largest, with max() .) (如果您知道它们都是相同的,或者您想要的是第一个,那么.iloc[0]速度当然比.min()快,但是,也许它们没有排序并且您想要最小..或最大,使用max() 。)

Then you can make a filename easily: 然后,您可以轻松地创建文件名:

>>> datestr = date.min().strftime("%Y%m%d")
>>> 'filename_{}.csv'.format(datestr)
'filename_20140620.csv'

Try using the datetime module. 尝试使用datetime模块。 Is this what you expect? 这是您所期望的吗?

import datetime
def _getToday():
        return datetime.date.today().strftime("%Y%m%d")
outpath = r'C:\test'
filename = "%s_%s.%s" % ("filename", _getToday() ,".csv")

print outpath + "\\" + filename

When using this with pd.ExcelWriter –this worked: 当与pd.ExcelWriter一起使用时,此pd.ExcelWriter有效:

datestr = tdy.strftime("%Y%m%d")

x = 'FileName_{}.xlsx'.format(datestr)

writer = pd.ExcelWriter(x, engine= "xlsxwriter")

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

相关问题 如何在python的csv中写入文件名和行数? - How to write the filename and rowcount in a csv in python? 在 Python 中编辑 CSV 文件名以附加到当前文件名 - Edit CSV filename in Python to append to the current filename Pandas:如何使用数据帧中的数据作为路径/文件名的一部分来编写csv文件 - Pandas: how to write csv file using data from a dataframe as part of path/filename 如何使用python中的DataFrame生成的结果写入csv? - How to write into csv using the results generated from a DataFrame in python? 如何遍历 Python 查询字符串中的日期范围并将结果附加到数据框/csv - How to loop through a date range in Python query string and append results to a dataframe/csv 从DataFrame python pandas写入csv - write to csv from DataFrame python pandas 使用 Output 路径将 Dataframe + 动态文件名写入 CSV - Write Dataframe + Dynamic Filename to CSV with Output Path 使用python将数据从csv导入到postgres DB时如何添加文件名和日期 - how to add filename and date when importing data from csv to postgres DB using python 如何在Python中将dict列表写入CSV并从CSV缓冲区创建熊猫数据框? - How to write a list of dicts to a csv and create a pandas dataframe from the CSV buffer in Python? 在Python中仅从DataFrame向CSV添加新值 - Append only new values to CSV from DataFrame in Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM