Pandas Datetime: Extract year, month, day, hour, minute, second and weekday from unidentified flying object (UFO) reporting date
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 1949-10-10 20:30:00 san marcos ... 29.883056 -97.941111 1 1949-10-10 21:00:00 lackland afb ... 29.384210 -98.581082 2 1955-10-10 17:00:00 chester (uk/england) ... 53.200000 -2.916667 3 1956-10-10 21:00:00 edna ... 28.978333 -96.645833 4 1960-10-10 20:00:00 kaneohe ... 21.418056 -157.803611 [5 rows x 11 columns] Year: 0 1949 1 1949 2 1955 3 1956 4 1960 Name: Date_time, dtype: int64 Month: 0 10 1 10 2 10 3 10 4 10 Name: Date_time, dtype: int64 Day: 0 10 1 10 2 10 3 10 4 10 Name: Date_time, dtype: int64 Hour: 0 20 1 21 2 17 3 21 4 20 Name: Date_time, dtype: int64 Minute: 0 30 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 Monday 1 Monday 2 Monday 3 Wednesday 4 Monday 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?
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics