I can't convert the date...

Asked 2 years ago, Updated 2 years ago, 21 views

The date I got from crawling is 22.01.16. If it comes out in this form and changes to date time, there is a bug that changes to an unexistent time. In this situation, how do I change the date to convert it correctly?

python

2022-09-20 11:30

1 Answers

>>> import pandas as pd

>>> df = pd.DataFrame({"Date":[ "22.01.16", "22.01.15", "22.01.14", "22.01.13" ]})

>>> pd.to_datetime(df["Date"], format="%y.%m.%d")
0   2022-01-16
1   2022-01-15
2   2022-01-14
3   2022-01-13
Name: Date, dtype: datetime64[ns]

>>> df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 4 entries, 0 to 3
Data columns (total 1 columns):
 #   #   Column  Non-Null Count  Dtype 
---  ------  --------------  ----- 
 0   Date    4 non-null      object
dtypes: object(1)
memory usage: 160.0+ bytes
>>> df["Date_datetime"] = pd.to_datetime(df["Date"], format="%y.%m.%d")
>>> df
       Date Date_datetime
0  22.01.16    2022-01-16
1  22.01.15    2022-01-15
2  22.01.14    2022-01-14
3  22.01.13    2022-01-13
>>> df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 4 entries, 0 to 3
Data columns (total 2 columns):
 #   #   Column         Non-Null Count  Dtype         
---  ------         --------------  -----         
 0   Date           4 non-null      object        
 1   Date_datetime  4 non-null      datetime64[ns]
dtypes: datetime64[ns](1), object(1)
memory usage: 192.0+ bytes


2022-09-20 11:30

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.