Apr-14-2023, 10:45 AM
I often use generators to process something line by line or element by element.
To convert a date, you should read the docs: https://docs.python.org/3/library/dateti...e.strptime
An example:
To convert a date, you should read the docs: https://docs.python.org/3/library/dateti...e.strptime
An example:
import io from datetime import date as Date from datetime import datetime as DateTime # 10 lines of fake data fake_file = io.StringIO("19260701,0.09,-0.22,-0.30,0.009\n" * 10) def transformer(file): """ Generator to exctract line by line data from a file. The seperator is a `,` and the first colum is a date formatted as: `YYYYMMDD` The remaing columns are converted to float. """ # iterating over a file-object yields lines # and the line ending is kept for line in fake_file: # date is the first element of row # and *rest consumes all remaining elements # (rest is a list) # rstrip removes tailing whitespaces date, *rest = line.rstrip().split(",") # converting all elements from rest to float values = list(map(float, rest)) # extracting the date # a regex could be used # but in this example I use slicing # year, month, day = map(int, (date[0:4], date[4:6], date[6:8])) # date = Date(year, month, day) # Another method to parse date on a single line date = DateTime.strptime(date, "%Y%m%d").date() # using iterable unpacking to get a flat list with # date, value1, value2, value3, ... yield [date, *values] for row in transformer(fake_file): print(row)
Output:[datetime.date(1926, 7, 1), 0.09, -0.22, -0.3, 0.009]
[datetime.date(1926, 7, 1), 0.09, -0.22, -0.3, 0.009]
[datetime.date(1926, 7, 1), 0.09, -0.22, -0.3, 0.009]
[datetime.date(1926, 7, 1), 0.09, -0.22, -0.3, 0.009]
[datetime.date(1926, 7, 1), 0.09, -0.22, -0.3, 0.009]
[datetime.date(1926, 7, 1), 0.09, -0.22, -0.3, 0.009]
[datetime.date(1926, 7, 1), 0.09, -0.22, -0.3, 0.009]
[datetime.date(1926, 7, 1), 0.09, -0.22, -0.3, 0.009]
[datetime.date(1926, 7, 1), 0.09, -0.22, -0.3, 0.009]
[datetime.date(1926, 7, 1), 0.09, -0.22, -0.3, 0.009]
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
All humans together. We don't need politicians!