w3resource
Python Pandas Exercises

Pandas Datetime: Extract year, month, day, hour, minute, second and weekday from unidentified flying object (UFO) reporting date

Pandas Datetime: Exercise-8 with Solution

Write a Pandas program to extract year, month, day, hour, minute, second and weekday from unidentified flying object (UFO) reporting date.

Sample Solution :

Python Code :

import pandas as pd
df = pd.read_csv(r'ufo.csv')
df['Date_time'] = df['Date_time'].astype('datetime64[ns]')
print("Original Dataframe:")
print(df.head())
print("\nYear:")
print(df.Date_time.dt.year.head())
print("\nMonth:")
print(df.Date_time.dt.month.head())
print("\nDay:")
print(df.Date_time.dt.day.head())
print("\nHour:")
print(df.Date_time.dt.hour.head())
print("\nMinute:")
print(df.Date_time.dt.minute.head())
print("\nSecond:")
print(df.Date_time.dt.second.head())
print("\nWeekday:")
print(df.Date_time.dt.weekday_name.head())

Sample Output:

Original Dataframe:
            Date_time                  city     ...       latitude   longitude
0 1910-06-01 15:00:00           wills point     ...      32.709167  -96.008056
1 1920-06-11 21:00:00                cicero     ...      40.123889  -86.013333
2 1929-07-05 14:00:00  buchanan  (or burns)     ...      43.642500 -118.627500
3 1931-06-01 13:00:00               abilene     ...      38.917222  -97.213611
4 1939-06-01 20:00:00              waterloo     ...      34.918056  -88.064167

[5 rows x 11 columns]

Year:
0    1910
1    1920
2    1929
3    1931
4    1939
Name: Date_time, dtype: int64

Month:
0    6
1    6
2    7
3    6
4    6
Name: Date_time, dtype: int64

Day:
0     1
1    11
2     5
3     1
4     1
Name: Date_time, dtype: int64

Hour:
0    15
1    21
2    14
3    13
4    20
Name: Date_time, dtype: int64

Minute:
0    0
1    0
2    0
3    0
4    0
Name: Date_time, dtype: int64

Second:
0    0
1    0
2    0
3    0
4    0
Name: Date_time, dtype: int64

Weekday:
0    Wednesday
1       Friday
2       Friday
3       Monday
4     Thursday
Name: Date_time, dtype: object

Python Code Editor:


Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Pandas program to create a plot to present the number of unidentified flying object (UFO) reports per year.
Next: Write a Pandas program to convert given datetime to timestamp.

What is the difficulty level of this exercise?