Day19.python time and date

Python time and date##

The datetime module is dedicated to time and date processing

The commonly used functions are as follows:

datetime.now() & datetime.today()

import datetime
 print(datetime.datetime.now())
 
 # datetime.today()
 #2020- 09- 2123:13:05.245157 print(datetime.datetime.today())
 #2020-09-2123:13:57.062886

datetime.strptime()

print(datetime.datetime.strptime('2020/08/09',format('%Y/%m/%d')))
 #2020- 08- 0900:00:00 print(datetime.datetime.strptime('20-08-09',format('%y-%m-%d')))
 #2020-08-0900:00:00

datetime.strftime()

Receive a time tuple, and return the local time expressed as a readable string, the format is determined by the parameter format.

 dt = datetime.datetime.now()print("======================")print('time:(%Y-%m-%d %H:%M:%S %f): ',dt.strftime('%Y-%m-%d %H:%M:%S %f'))print('time:(%Y-%m-%d %H:%M:%S %p): ', dt.strftime('%y-%m-%d %I:%M:%S %p'))print('Abbreviation of the week%%a: %s '% dt.strftime('%a'))print('All week%%A: %s '% dt.strftime('%A'))print('Month abbreviation%%b: %s '% dt.strftime('%b'))print('Month batch%%B: %s '% dt.strftime('%B'))print('Date time%%c: %s '% dt.strftime('%c'))print('Today is the first of this week%s days'% dt.strftime('%w'))print('Today is the first of this year%s days'% dt.strftime('%j'))print('This week is the first of the year%s week'% dt.strftime('%U'))print('Today is the first of the month%s days'% dt.strftime('%d'))'''
 ====================== time:(%Y-%m-%d %H:%M:%S %f):2020-09-2123:30:51573645time:(%Y-%m-%d %H:%M:%S %p):20-09-2111:30:51 PM
 Abbreviation of the week%a: Mon
 All week%A: Monday
 Month abbreviation%b: Sep
 Month batch%B: September
 Date time%c: Mon Sep 2123:30:512020
 Today is the first day of the week
 Today is the 265th day of this year
 This week is the 38th week of the year
 Today is the 21st day of the month
 '''

Application scenarios of time and date##

1. Introduction###

When writing code, it often involves the mutual conversion of time, date, and time stamp.

2. Example

 # Import module
 import time, datetime

2.1 Date of str type is converted to timestamp####

 # Character type time
 
 testStr ='2020-09-21 23:26:33'
 
 # Convert to time array
 timeArray = time.strptime(testStr,"%Y-%m-%d %H:%M:%S")print(timeArray)
 
 # timeArray can call tm_year etc.
 print(timeArray.tm_year)  # 2020
 
 # Convert to timestamp
 timeStamp =int(time.mktime(timeArray))print(timeStamp)  # 1600701993
 
 # The result is as follows
 time.struct_time(tm_year=2020, tm_mon=9, tm_mday=21, tm_hour=23, tm_min=26, tm_sec=33, tm_wday=0, tm_yday=265, tm_isdst=-1)20201600701993

2.2 Change the display format of str type date####

 testStr1 ="2020-09-21 23:40:00"
 # Convert to array
 timeArray = time.strptime(testStr1,"%Y-%m-%d %H:%M:%S")
 # Convert to other display format
 otherStyleTime = time.strftime("%Y/%m/%d %H:%M:%S", timeArray)print(otherStyleTime)
 
 tss3 ="2020/09/21 23:40:00"
 timeArray = time.strptime(tss3,"%Y/%m/%d %H:%M:%S")
 otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)print(otherStyleTime)"""
 - - - - - - - - - - - - - - - - - - - - - - - 2020 /09/2123:40:002020-09-2123:40:00======================"""

2.3 The timestamp is converted to a date in the specified format

 # Use time
 timeStamp =1600701993
 timeArray = time.localtime(timeStamp)
 otherStyleTime = time.strftime("%Y--%m--%d %H:%M:%S", timeArray)print(otherStyleTime)  # 2020--09--2123:26:33
 # Use datetime
 timeStamp =1600101993
 dateArray = datetime.datetime.fromtimestamp(timeStamp)
 otherStyleTime = dateArray.strftime("%Y--%m--%d %H:%M:%S")print(otherStyleTime)  # 2020--09--1500:46:33
 # Use datetime, specify UTC time, the difference is 8 hours
 timeStamp =1600201993
 dateArray = datetime.datetime.utcfromtimestamp(timeStamp)
 otherStyleTime = dateArray.strftime("%Y--%m--%d %H:%M:%S")print(otherStyleTime)  # 2020--09--1520:33:13

2.4 Get the current time and display it in the specified format

print("+++++++++++++++++++++++++++++++++++++++++++")
 # time to get the current timestamp
 now =int(time.time())     # 1533952277
 timeArray = time.localtime(now)print(timeArray)
 otherStyleTime = time.strftime("%Y--%m--%d %H:%M:%S", timeArray)print(otherStyleTime)
 
 # The result is as follows
 """
 time.struct_time(tm_year=2020, tm_mon=9, tm_mday=21, tm_hour=23, tm_min=45, tm_sec=53, tm_wday=0, tm_yday=265, tm_isdst=0)2020--09--2123:45:53"""
 
 
 # datetime to get the current time, array format
 now = datetime.datetime.now()print(now)
 otherStyleTime = now.strftime("%Y--%m--%d %H:%M:%S")print(otherStyleTime)
 
 # The results are as follows:
 
 """
 2020-09-2123:45:53.5434872020--09--2123:45:53"""

Date function time module function##

The string mentioned here is not a string in the general sense. It means that when reading data of date type, if the string has not been parsed in time, it is not a date type, then how should the string at this time be related to the timestamp? Convert between?

There are three commonly used forms of date and time:

  1. Floating point number in seconds
  2. struct_time tuple
  3. Time string
import time;  #Introduce the time module
 ticks = time.time()print("The current timestamp is:", ticks)
 
 The current timestamp is:1600704429.9781017
Floating point number in seconds is converted to time tuple#####
 tm_struct = time.localtime(ticks)print(tm_struct)
 
 time.struct_time(tm_year=2020, tm_mon=9, tm_mday=22, tm_hour=0, tm_min=8, tm_sec=2, tm_wday=1, tm_yday=266, tm_isdst=0)

Sometimes we need to get Greenwich Mean Time, then we can use the time.gmtime() function:

 # Greenwich Mean Time
 print(time.gmtime(ticks))
 
 
 time.struct_time(tm_year=2020, tm_mon=9, tm_mday=21, tm_hour=16, tm_min=9, tm_sec=18, tm_wday=0, tm_yday=265, tm_isdst=0)
The time tuple is converted to a floating point number in seconds
print(time.mktime(tm_struct))1600704621.0
Time tuple is converted to time string

There are many conversion methods, the simplest is asctime():

 time_str = time.asctime( tm_struct )print(time_str)"""
 Tue Sep 2200:12:142020"""

If you want to precisely control the format, we can use strftime():

 tm_1=time.strftime("%Y-%m-%d %H:%M:%S", tm_struct)
 tm_2=time.strftime("%a %b %d %H:%M:%S %Y", tm_struct)print(tm_1)print(tm_2)"""
 2020-09-2200:14:13
 Tue Sep 2200:14:132020"""
Time string is converted to time tuple#####

The function time.strptime() can complete this conversion, the following is an example

 tm2_struct = time.strptime('2020-09-22 01:34:50',"%Y-%m-%d %H:%M:%S")print(tm2_struct)"""
 time.struct_time(tm_year=2020, tm_mon=9, tm_mday=22, tm_hour=1, tm_min=34, tm_sec=50, tm_wday=1, tm_yday=266, tm_isdst=-1)"""
Floating point number in seconds is converted to time string

time.ctime() is similar to time.asctime(), please see the following example:

 tm_3=time.ctime(ticks)print(tm_3)"""
 Tue Sep 2200:17:542020"""
 # If you want to precisely control the output string, I haven't found any existing functions. It is estimated that it can only be converted into a tuple first, and then formatted into a string.
 # I wrote a conversion function:
 
 def time2str(ticks, fmt='%a %b %d %H:%M:%S %Y'):
  tm = time.localtime(ticks)return time.strftime(fmt, tm)
The time string is converted to a floating point number in seconds
 def str2time(str, fmt='%a %b %d %H:%M:%S %Y'):
  tm = time.strptime(str, fmt)return time.mktime(tm)
 
 # Here is also a reference function

Homework practice

Generate intermediate date based on start and end date##

pandas.to_datetime(arg, errors ='raise', utc = None, format = None, unit = None) convert a string to a date function

 # Convert time string format, method two:
 import pandas as pd
 start = pd.to_datetime("20200922")print("===================================")print(start)
 s=start.strftime('%Y-%m-%d') #Convert datetime to a string and use'%Y-%m-%d'Format output
 print(s)print("===================================")"""
 ==================================2020-09-2200:00:002020-09-22=================================="""

**Write function: **

import time;  #Introduce the time module
 from pandas import DatetimeIndex
 
 
 def date_range(cls, start=None, end=None, periods=None, freq=None, input_format=None, out_format=None):"""
  Generate time series
  : param start:Sequence start time
  : param end:Sequence end time,When start is given,End time contains end
  : param periods: int,The length of the generated time series
  : param freq:The time interval to generate the time series
  : param out_format:Whether to output the formatted string,Specify the output format for output."%Y-%m-%d %H:%M:%S":param input_format:If start or end is a string and the time format cannot be inferred automatically, you need to specify the format
  : return:[date or date_str]"""
 
 start = pd.to_datetime("20200918")
 end = pd.to_datetime("20200922")
 pd.date_range(start, end)DatetimeIndex(['2020-09-28','2020-09-29','2020-09-30','2020-09-13','2020-06-01','2020-06-02'])

Example 1:

 # example 1:
 dates =["20200912","20200922"]
 def create_dates(dates):"""
  : param dates:["20200912","20200922"]:return:"""
  start = pd.to_datetime(dates[0])
  end = pd.to_datetime(dates[1])
  dates = pd.date_range(start, end)  #Generate a list of time strings
  dates = dates.strftime('%Y%m%d')   #Format time data
  returnlist(dates)print("example 1")print(create_dates(dates))"""
 example 1['20200912','20200913','20200914','20200915','20200916','20200917','20200918','20200919','20200920','20200921','20200922']"""

**Example 2: **

 # Example 2
 
 df = pd.DataFrame({'year':[2019,2020],'month':[2,3],'day':[4,5]})
 pd.to_datetime(df)print("Example 2")print(pd.to_datetime(df))"""
 Example 202019-02-0412020-03-05
 dtype: datetime64[ns]"""

Recommended Posts

Day19.python time and date