w3resource

Pandas Series: dt.to_pydatetime() function

Series.dt.to_pydatetime() function

The to_pydatetime() function is used to get the data as an array of native Python datetime objects.
Timezone information is retained if present.

Syntax:

Series.dt.to_pydatetime(self)
Pandas Series: dt.to_pydatetime() function

Returns: numpy.ndarray
Object dtype array containing native Python datetime objects.

Example:

Python-Pandas Code:

import numpy as np
import pandas as pd
s = pd.Series(pd.date_range('20190210', periods=2))
s

Output:

0   2019-02-10
1   2019-02-11
dtype: datetime64[ns]

Python-Pandas Code:

import numpy as np
import pandas as pd
s = pd.Series(pd.date_range('20190210', periods=2))
s.dt.to_pydatetime()

Output:

array([datetime.datetime(2019, 2, 10, 0, 0),
       datetime.datetime(2019, 2, 11, 0, 0)], dtype=object)

Example - pandas’ nanosecond precision is truncated to microseconds:

Python-Pandas Code:

import numpy as np
import pandas as pd
s = pd.Series(pd.date_range('20190210', periods=2, freq='ns'))
s

Output:

0   2019-02-10 00:00:00.000000000
1   2019-02-10 00:00:00.000000001
dtype: datetime64[ns]

Python-Pandas Code:

import numpy as np
import pandas as pd
s = pd.Series(pd.date_range('20190210', periods=2, freq='ns'))
s.dt.to_pydatetime()

Output:

array([datetime.datetime(2019, 2, 10, 0, 0),
       datetime.datetime(2019, 2, 10, 0, 0)], dtype=object)
Pandas Series: dt.to_pydatetime() function

Previous: Series.dt.to_period() function
Next: Series.dt.tz_localize() function



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/pandas/series/series-dt-to_pydatetime.php