Dataframe change the column with the date
-
How to turn 'Timestamp' into a pole with a normal date like
1/14/2009
? http://file.sampo.ru/w3862t/df = pd.read_csv('temp.csv') df
-
Use the parameter. https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html :
df = pd.read_csv("temp.csv", parse_dates=["Timestamp"])
result:
In [114]: df.head() Out[114]: Timestamp F 0 2012-01-03 1 1 2012-01-06 1 2 2012-01-09 1 3 2012-01-12 1 4 2012-01-15 1
In [115]: df.dtypes
Out[115]:
Timestamp datetime64[ns] # <-- NOTE!!!
F int64
dtype: object
If there is at least one line in the data where time does not indicate midnight (
00:00:00
Then Pandas will show both date and time:In [116]: df = pd.read_csv("temp.csv", parse_dates=["Timestamp"])
In [117]: df.head()
Out[117]:
Timestamp F
0 2012-01-03 21:59:00 1
1 2012-01-06 00:00:00 1
2 2012-01-09 00:00:00 1
3 2012-01-12 00:00:00 1
4 2012-01-15 00:00:00 1
The time component can be cut as follows:
In [118]: df["Timestamp"] = df["Timestamp"].dt.floor("D")
In [119]: df.head()
Out[119]:
Timestamp F
0 2012-01-03 1
1 2012-01-06 1
2 2012-01-09 1
3 2012-01-12 1
4 2012-01-15 1
If you need to convert the date to a given format, it's done:
df["timestamp_str"] = df["Timestamp"].dt.strftime("%m/%d/%Y")
result:
In [121]: df.head()
Out[121]:
Timestamp F timestamp_str
0 2012-01-03 1 01/03/2012
1 2012-01-06 1 01/06/2012
2 2012-01-09 1 01/09/2012
3 2012-01-12 1 01/12/2012
4 2012-01-15 1 01/15/2012In [122]: df.dtypes
Out[122]:
Timestamp datetime64[ns]
F int64
timestamp_str object # <-- NOTE!!!
dtype: object
NOTE: After this transformation, you will get the lines instead of the dates and, as a consequence, you will not be able to use any function to deal with dates/time, including arithmetic dates. Usually, dates are converted to a specific format only before they are retained in text form or for display/graph.