Understanding Python Dataframe to Datetime Conversion

Asked 2 years ago, Updated 2 years ago, 38 views

I have a question. I'm a beginner at Python, so please let me know.
I'd like to convert the str type in the dataFrame of the pandas to the datetime type in bulk to get the data of the month and day.

I understand that the conversion to DataFrame type → datetime type can be converted with to_datetime, but I don't know how to extract the month/day data from it.

Also, I would appreciate it if you could tell me how to convert a to_datetime conversion into a str type.

<table>
<tr><th>2017-04-0100:00</th>Saturday>/tr>
<tr>th>2017-04-0101:00</th>Saturday>/tr>
<tr>th>2017-04-0102:00</th>Saturday>/tr>
<tr>th>2017-04-0103:00</th>Saturday>/tr>
<tr><th>2017-04-0104:00</th>Saturday>/th>>
</table>

python python3 pandas

2022-09-30 14:39

2 Answers

From .dt, you can use datetime methods.

import pandas as pd

s=pd.Series([
    '20170401 12:00:00',
    '20170401 13:00:00',    
    '20170401 14:00:00',        
])
print(s)
print('---')

s_dt=pd.to_datetime(s)
print(s_dt)
print('---')

print(s_dt.dt.year)
print('---')

print(s_dt.dt.month)
print('---')

print(s_dt.dt.day)
print('---')

Output

 020170401 12:00:00
1    20170401 13:00:00
2    20170401 14:00:00
dtype:object
---
0   2017-04-01 12:00:00
1   2017-04-01 13:00:00
2   2017-04-01 14:00:00
dtype —datetime64 [ns]
---
0    2017
1    2017
2    2017
dtype —int64
---
0    4
1    4
2    4
dtype —int64
---
0    1
1    1
2    1
dtype —int64
---


2022-09-30 14:39

It seems like it's been quite a while, but just for your information.
I didn't know what the original data was like, so I created a 365-day DataFrame type from April 1st, 2017, and wrote it out using the following steps.

import numpy as np
import pandas aspd

# Created DataFrame from April 1st to March 31st of the following year
date=np.array('2017-04-01', dtype=np.datetime64)
df=pd.DataFrame (date+np.range(365), columns=['date'])

# Write down the date and time in order.
for row in range (len(df)) :
    print(df['date'][row].strftime('%m of %d'))

We first created an array from datetime64 and then DataFrame.In this case, instead of using to_datetime, the column 'data' is extracted using strftime ('%m' or '%d') specifying the month or day.
If the original data is written in Japanese (April 1, 2017), it must be converted once.
The following is only for 3 days, but it is for conversion from Japanese notation.It's almost the same.

date_jp=['April 1, 2017', 'April 2, 2017', 'April 3, 2017']
df_jp=pd.DataFrame(date_jp, columns=['date'])
df_jp['date'] = pd.to_datetime(df_jp['date'], format='%Y year %m month %d' day')
for row in range (len(df_jp)) :
    print(df_jp['date'][row].strftime('%m of %d'))

After converting the list to DataFrame, it recognizes it as datetime and extracts the month and day with a for statement.


2022-09-30 14:39

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.