I need to write the following dataframe to csv:
prodid value timestamp
322 4 2021-11-03 17:32:12.252
123 34 2021-11-03 18:42:12.602
...
or
import datetime
df = pd.DataFrame([(0, 4, datetime.datetime.strptime("2021-11-03 14:32:13.4)02", "%Y-%m-%d %H:%M:%S.%f"),
(1, 34, datetime.datetime.strptime("2021-11-03 18:42:12.602", "%Y-%m-%d %H:%M:%S.%f"))],
columns=['prodid', 'value', 'timestamp'])
When I write this to csv in a StringIO
buffer:
import io
io_buff = io.StringIO()
df.to_csv(io_buff, sep='\t', header=False, index=False)
column timestamp
is no longer preserved as datetime
. When I further process this io_buff
, such as writing it to a Postgres table, column timestamp
is written as numeric
.
How do I preserve the timestamp format when writing it with pd.to_csv()
?