-
-
Notifications
You must be signed in to change notification settings - Fork 19.1k
Description
Code Sample, a copy-pastable example if possible
>>> import pandas as pd
>>> mydf = pd.DataFrame.from_dict(dict(dt=[pd.Timestamp('2000-01-01'),pd.Timestamp('2000-01-01 00:00:00.000000001')]))
>>> print(mydf.to_csv(index=False))
dt
2000-01-01 00:00:00.000000000
2000-01-01 00:00:00.000000001
>>> print(mydf.to_csv(index=False,date_format='%Y-%m-%dT%H:%M:%S.%f'))
dt
2000-01-01T00:00:00.000000
2000-01-01T00:00:00.000000
Problem description
ISO-8601 specifies that the 'T' separator is optional in contexts where there is no ambiguity with other 8601 date or time formats. I'm trying to make some CSV files and am trying to be very strict with what I emit because I don't know how they'll be consumed.
It'd be really nice to be able to preserve full precision in the data but still have that separator character present and as far as I am aware, there is no Python Datetime format string which displays nanoseconds.
The shortest alternative I can come up with for this is the following (and I am not 100% sure this will work correctly):
tmp_df = mydf
dt_cols = mydf.select_dtypes(include='datetime64').columns
tmp_df[dt_cols] = tmp_df[dt_cols].applymap(lambda x:str(x.to_datetime64()))
tmp_df.to_csv(index=False)
Expected Output
dt
2000-01-01T00:00:00.000000000
2000-01-01T00:00:00.000000001
Output of pd.show_versions()
INSTALLED VERSIONS
commit: None
python: 3.6.8.final.0
python-bits: 64
OS: Linux
OS-release: 3.10.0-327.36.3.el7.x86_64
machine: x86_64
processor: x86_64
byteorder: little
LC_ALL: None
LANG: en_US.UTF-8
LOCALE: en_US.UTF-8
pandas: 0.24.2
pytest: 3.6.4
pip: 19.1.1
setuptools: 41.0.1
Cython: None
numpy: 1.16.4
scipy: None
pyarrow: 0.13.0
xarray: None
IPython: 7.5.0
sphinx: None
patsy: None
dateutil: 2.8.0
pytz: 2019.1
blosc: None
bottleneck: None
tables: None
numexpr: None
feather: None
matplotlib: 2.2.4
openpyxl: 2.5.14
xlrd: 1.1.0
xlwt: None
xlsxwriter: None
lxml.etree: None
bs4: None
html5lib: None
sqlalchemy: 1.2.19
pymysql: None
psycopg2: None
jinja2: 2.10.1
s3fs: None
fastparquet: None
pandas_gbq: None
pandas_datareader: None
gcsfs: None