import pandas as pd from pathlib import Path def sortcsvbydate(filepath): Load the CSV…
- User
import pandas as pd from pathlib import Path
def sort_csv_by_date(file_path): # Load the CSV file into a DataFrame df = pd.read_csv(file_path)
# Convert the 'Date' column to datetime format (adjust the format as per your CSVs) df['Date'] = pd.to_datetime(df['Date'], format ='%Y-%m-%d') # Adjust format as needed # Sort the DataFrame based on the 'Date' in ascending order to get the latest at the bottom df = df.sort_values(by='Date', ascending = True) # Save the sorted DataFrame back to the same CSV (overwrites) df.to_csv(file_path, index=False) print(f"Sorted {file_path}")Path to the base directory containing your 4 separate folders with CSV files
base_directory_path = r"..\downloaded_files\Binance\test"
List of folders to iterate through
folders = [d for d in Path(base_directory_path).iterdir() if d.is_dir()]
Loop through each folder and then through each CSV file within them
for folder in folders: for file_path in folder.glob('*.csv'): sort_csv_by_date(file_path)
Traceback (most recent call last): File "C:\Users\Fazel\PycharmProjects\indicators_calculate\02_sort_descending_date.py", line 29, in sort_csv_by_date(file_path) File "C:\Users\Fazel\PycharmProjects\indicators_calculate\02_sort_descending_date.py", line 10, in sort_csv_by_date df['Date'] = pd.to_datetime(df['Date'], format ='%Y-%m-%d') # Adjust format as needed File "C:\Users\Fazel\PycharmProjects\indicators_calculate\venv\lib\site-packages\pandas\core\tools\datetimes.py", line 1067, in to_datetime values = convert_listlike(arg._values, format) File "C:\Users\Fazel\PycharmProjects\indicators_calculate\venv\lib\site-packages\pandas\core\tools\datetimes.py", line 433, in _convert_listlike_datetimes return _array_strptime_with_fallback(arg, name, utc, format, exact, errors) File "C:\Users\Fazel\PycharmProjects\indicators_calculate\venv\lib\site-packages\pandas\core\tools\datetimes.py", line 467, in _array_strptime_with_fallback result, tz_out = array_strptime(arg, fmt, exact=exact, errors=errors, utc=utc) File "strptime.pyx", line 501, in pandas._libs.tslibs.strptime.array_strptime File "strptime.pyx", line 451, in pandas._libs.tslibs.strptime.array_strptime File "strptime.pyx", line 587, in pandas._libs.tslibs.strptime._parse_with_format ValueError: unconverted data remains when parsing with format "%Y-%m-%d": " 23:00:00", at position 0. You might want to try: - passing
formatif your strings have a consistent format; - passingformat='ISO8601'if your strings are all ISO8601 but not necessarily in exactly the same format; - passingformat='mixed', and the format will be inferred for each element individually. You might want to usedayfirstalongside this.Process finished with exit code 1
- Assistant
The error you encountered suggests that the date strings in your CSV files also contain time information (e.g., "23:00:00"), but your specified format (
'%Y-%m-%d') does not account for this time portion. This mismatch between the actual data format and the one you specified inpd.to_datetimeis causing the error.Here’s an updated version of your
sort_csv_by_datefunction that should handle the datetime including the time portion: - User
update the code so it sort datas based on my "Unix" column instead of "Date"
- Assistant
Certainly! If you want to sort your CSV files based on a "Unix" timestamp column instead of a "Date" column, you can easily adjust the script. The "Unix" column typically contains integer or float timestamps representing the number of seconds (or milliseconds) since the Unix epoch (January 1, 1970).
Here's how you can modify your function to sort by "Unix" timestamp: