Search code examples
pythonpython-3.xdataframepython-datetime

Facing problem in converting into datetime


df_non_holidays=pd.read_csv("holidays.csv")
    
print(df_non_holidays["date"])

    0     25-06-21
    1     28-06-21
    2     29-06-21
    3     30-06-21
    4     01-07-21
    5     02-07-21
    6     05-07-21
    7     06-07-21
    8     07-07-21
    9     08-07-21
    10    09-07-21
    11    12-07-21
    12    13-07-21
    13    14-07-21
    14    15-07-21
    15    16-07-21
    16    19-07-21
    17    20-07-21
    18    22-07-21
    19    23-07-21
    20    26-07-21
    21    27-07-21
    22    28-07-21
    23    29-07-21
    24    30-07-21
    Name: date, dtype: object
df_non_holidays["date"]= pd.to_datetime(df_non_holidays["date"])

0    2021-06-25
1    2021-06-28
2    2021-06-29
3    2021-06-30
4    2021-01-07
5    2021-02-07
6    2021-05-07
7    2021-06-07
8    2021-07-07
9    2021-08-07
10   2021-09-07
11   2021-12-07
12   2021-07-13
13   2021-07-14
14   2021-07-15
15   2021-07-16
16   2021-07-19
17   2021-07-20
18   2021-07-22
19   2021-07-23
20   2021-07-26
21   2021-07-27
22   2021-07-28
23   2021-07-29
24   2021-07-30
Name: date, dtype: datetime64[ns]

after converting , from index no:4 , it is changing in month and date differently.. does anything wrong in approach in converting object into datetime..

please guide me..


Solution

  • You also need to pass the format string, or you can pass dayfirst=True as well if you don't want to pass the format. But passing dayfirst may not always work for all type of datetime string values; however, passing format is always going to work if you pass the right format.

    >>> pd.to_datetime(df_non_holidays["date"], format='%d-%m-%y')
    
    0    2021-06-25
    1    2021-06-28
    2    2021-06-29
    3    2021-06-30
    4    2021-07-01
    5    2021-07-02
    6    2021-07-05
    7    2021-07-06
    8    2021-07-07
    9    2021-07-08
    10   2021-07-09
    11   2021-07-12
    12   2021-07-13
    13   2021-07-14
    14   2021-07-15
    15   2021-07-16
    16   2021-07-19
    17   2021-07-20
    18   2021-07-22
    19   2021-07-23
    20   2021-07-26
    21   2021-07-27
    22   2021-07-28
    23   2021-07-29
    24   2021-07-30
    Name: date, dtype: datetime64[ns]