程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Teach you to use Python to get 30 kinds of information from dates, such as year, month, day and week

編輯:Python

Catalog

1 Calculate the year, day, hour, minute and second of the date , week , Week …

2 Calculate the day of the year , Number one 10 minute , Date to value

3 Judge whether the date is a leap year , The beginning of the year and the end of the year , At the beginning and end of the month …

4 String period , season

5for Cycle fast calculation

6 Time interval days calculation

Add :Python Date get the date of today and yesterday

summary

This time we introduce date data processing .

use python Date data is processed by the method in , We can get a lot of useful information , For example, mm / DD / yyyy , week , Week , Quarter, etc , Share work and data competitions here 30 There are more than common conversion methods .

1 Calculate the year, day, hour, minute and second of the date , week , Week …

use pandas Of read_excel() Method reading excel Table data , Put... In the table " date " Column to date format

import pandas as pdimport numpy as npimport datetimedf = pd.read_excel('./ Date question .xlsx')# Convert the date column to date format df[' date '] = pd.to_datetime(df[' date '])

dt The module can easily obtain the basic attributes of the date

# Transfer to mm / DD / yyyy format ( String text )df[' Specific date '] = df[' date '].apply(lambda x: x.strftime('%Y%m%d'))df[' year ']=df[' date '].dt.year df[' quarter ']=df[' date '].dt.quarterdf[' month ']=df[' date '].dt.monthdf[' Japan ']=df[' date '].dt.day df[' What day ']=df[' date '].dt.dayofweekdf[' Week ']=df[' date '].dt.weekdf[' when ']=df[' date '].dt.hourdf[' branch ']=df[' date '].dt.minutedf[' second ']=df[' date '].dt.second

2 Calculate the day of the year , Number one 10 minute , Date to value

Through the sky , when , The four operations of cent convert the date into serial numerical data

df[' The day of the year ']=df[' date '].dt.dayofyeardf[' The first few minutes of the day ']=df[' date '].apply(lambda x: x.minute + x.hour*60) df[' How many times of the day 10 minute '] = df[' when '] * 6 + df[' branch '] // 10df[' The number '] = df[" date "].values.astype(np.int64) // 10 ** 9# Transfer to month and year ( The number )df[' years '] = df[' date '].dt.year * 100 + df[' date '].dt.month

3 Judge whether the date is a leap year , The beginning of the year and the end of the year , At the beginning and end of the month …

apply() and lambda() Methods use . python in 2 A powerful higher-order function .

df[' Leap year or not '] = df[' date '].apply(lambda x: x.is_leap_year) # Leap year or not df[' Is it at the beginning of the month '] = df[' date '].apply(lambda x: x.is_month_start) # Is it at the beginning of the month df[' Month end '] = df[' date '].apply(lambda x: x.is_month_end) # end of the month df[' Is it at the beginning of the season '] = df[' date '].apply(lambda x: x.is_quarter_start) # Beginning of quarter df[' End of season '] = df[' date '].apply(lambda x: x.is_quarter_end) # Quarter end df[' Whether the beginning of the year '] = df[' date '].apply(lambda x: x.is_year_start) # Beginning of the year df[' Whether the end of the year '] = df[' date '].apply(lambda x: x.is_year_end) # End of the year df[' Is it a weekend '] = df[' date '].apply(lambda x: True if x.dayofweek in [5, 6] else False) # Is it a weekend df.loc[((df[' when '] >= 8) & (df[' when '] < 22)), ' Whether business hours '] = True

4 String period , season

Construct a dictionary , use map Method to replace .

period_dict ={ 23: ' Late at night ', 0: ' Late at night ', 1: ' Late at night ', 2: ' In the morning ', 3: ' In the morning ', 4: ' In the morning ', 5: ' In the morning ', 6: ' In the morning ', 7: ' In the morning ', 8: ' In the morning ', 9: ' In the morning ', 10: ' In the morning ', 11: ' In the morning ', 12: ' At noon, ', 13: ' At noon, ', 14: ' Afternoon ', 15: ' Afternoon ', 16: ' Afternoon ', 17: ' Afternoon ', 18: ' In the evening ', 19: ' evening ', 20: ' evening ', 21: ' evening ', 22: ' evening ',}df[' Period of time ']=df[' when '].map(period_dict)# Which quarter of the year season_dict = { 1: ' In the spring ', 2: ' In the spring ', 3: ' In the spring ', 4: ' In the summer ', 5: ' In the summer ', 6: ' In the summer ', 7: ' In the fall ', 8: ' In the fall ', 9: ' In the fall ', 10: ' In the winter ', 11: ' In the winter ', 12: ' In the winter ',}df[' season ']=df[' month '].map(season_dict)

5for Cycle fast calculation

python Medium getattr() Method

time_features = ['year', 'month', 'quarter', 'week', 'day', 'dayofweek', 'dayofyear']dtype = np.int16for time_feature in time_features: df[time_feature] = getattr(df[' date '].dt, time_feature).astype(dtype)

6 Time interval days calculation

The date is compared with a specified date or today's date , Calculate the number of days between

# Set the initial time base_time = datetime.datetime.strptime('2021-06-01', '%Y-%m-%d')# Calculate the time difference df[' Time difference '] = df[' date '].apply(lambda x: x-base_time).dt.days # Days away from today df[' Days between '] = list(map(lambda x: x.days, pd.to_datetime('today') - df[' date ']))

Add :Python Date get the date of today and yesterday import timefrom datetime import datetime, date, timedelta# The current date now_date = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())print("now_date: {}".format(now_date))# Date of current time year = datetime.now().yearmonth = datetime.now().monthday = datetime.now().dayprint(f"year: {year}, month: {month}, day: {day}")# yesterday month_yesterday = (date.today() + timedelta(days=-1)).monthday_yesterday = (date.today() + timedelta(days=-1)).dayprint(f"month_yesterday: {month_yesterday}, day_yesterday: {day_yesterday}")

Output results :

now_date: 2022-06-01 11:22:11
year: 2022, month: 6, day: 1
month_yesterday: 5, day_yesterday: 31

summary

This is about using python Get the year... From the date 、 month 、 Day and week 30 This is the end of the information article , More about python Please search the previous articles of software development network or continue to browse the relevant articles below. I hope you will support software development network more in the future !



  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved