简体   繁体   English

Python:从CSV文件提取每日/每小时余额

[英]Python: extract daily/hourly balance from a CSV file

I have a long file which in particular has these two columns: 我有一个长文件,尤其是这两列:

   Balance     Time
   1000.01     2015-08-23 19:53:23
   1235.21     2015-08-23 17:32:42
    394.33     2015-08-22 23:32:12
    534.45     2015-08-22 13:44:12
    235.21     2015-08-22 13:22:51

How can I write to a list/vector the last balance of the day (eventually the hour HH:59:59) for all the rows? 如何将所有行的一天的最后一天余额(最后是小时HH:59:59)写入列表/向量? Perhaps using SQLite? 也许使用SQLite?

UPDATE 更新

I found a solution once extracted an array with times dates and balance bal from the csv file but I wonder if there is a less ugly way to do it. 我发现一个解决方案,一旦从csv文件中提取了一个带有日期和平衡bal的数组,但是我想知道是否有一种不太丑陋的方法。 Maybe using pandas. 也许使用熊猫。

    import datetime as dt
    delta=dt.timedelta(hours=1)            
    new_date=dt.datetime.strptime(start_date, "%Y-%m-%d %H:%M:%S")+delta
    for i in range(len(bal)):
        if dt.datetime.strptime(dates[i], "%Y-%m-%d %H:%M:%S")>new_date:
            hours_diff=int((dt.datetime.strptime(dates[i], "%Y-%m-%d %H:%M:%S")-new_date).total_seconds()/3600)
            while dt.datetime.strptime(dates[i], "%Y-%m-%d %H:%M:%S")>new_date:
                hourly_time.append(dt.datetime.strftime(new_date,"%Y-%m-%d %H:%M:%S"))
                new_date+=delta
                hourly_bal.append(hourly_bal[-1])
            hourly_bal[-1]=bal[i-1]
    hourly_time.append(dt.datetime.strftime(new_date,"%Y-%m-%d %H:%M:%S"))
    hourly_bal.append(bal[-1])

Use pandas - it's great for handling time series data. 使用pandas -非常适合处理时间序列数据。

Assuming the output you want is something like this? 假设您想要的输出是这样的?

   Balance     Time                   LastBalance
   1000.01     2015-08-23 19:53:23    235.21
   1235.21     2015-08-23 17:32:42    235.21
    235.21     2015-08-22 17:32:42    -

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

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