[fundamentals of Python data analysis-3] Python date and time and common processing methods

0. Introduction

The last article introduced the scalar type of Python. In this article, I will introduce the date and time of Python and its common processing methods!

1. Introduction to Python time type

There are several time representation methods commonly used in Python:

  • time stamp

  • Formatted time string

  • Time of the time module struct_ Time class

  • Datetime class of datetime module

The timestamp is also called Unix time and POSIX time. It represents the number of milliseconds elapsed from 0:0:0 on January 1, 1970 GMT to now. Its value is of float type. However, Python returns the number of seconds. It should be noted that the timestamp is a difference, and its value is independent of the time zone.

The formatted time string is a string like '2022-01-01 13:14:52'

The time module and the datetime module are described below.

2.time module and datetime module

Python provides time module and datetime module, which I will briefly introduce respectively.

2.1 time module

Time module I mainly introduce two functions: time Time() and time Localtime() function

1) time.time() function

time. The time() function returns a timestamp, which is the number of seconds since 1970-1-1 0:00:00

import time
time.time()
# Return results
1641043618.381585

2) time.localtime([secs]) function

​ time. The Localtime ([secs]) function returns a struct of the local time corresponding to the specified timestamp_ Time object. The parameter is a timestamp and needs to be passed in manually. If the parameter is not passed in, the function will return the local time when the function is executed by default.

import time
time.localtime(1641043618.381585)   # Incoming parameters
time.struct_time(tm_year=2022, tm_mon=1, tm_mday=1, tm_hour=21, tm_min=26, tm_sec=58, tm_wday=5, tm_yday=1, tm_isdst=0)
# The result is struct_ The time object indicates that the time stamp 1641043618.381585 corresponds to January 1, 2022, 21:26:58 seconds. January 1 is the sixth day of the week and the first day of the year, that is, 2022, tm_isdst indicates whether it is daylight saving time
import time
time.localtime()   # Do not pass in parameters
# The result returns the current local time
time.struct_time(tm_year=2022, tm_mon=1, tm_mday=1, tm_hour=21, tm_min=38, tm_sec=34, tm_wday=5, tm_yday=1, tm_isdst=0)

Readers may be interested in struct_ There are doubts about the attributes in the time object, so the following will briefly introduce the meaning of each attribute:

In struct module_ Property interpretation in time object
Attribute name Description / meaning
tm_year particular year
tm_month Month, the value range is [1,12]
tm_day The day of a month. The value range is [1, 31]
tm_hour Hour, value range is [0, 23]
tm_min Minutes, the value range is [0, 59]
tm_sec Second, the value range is [0, 61] (60 or 61 is leap second)
tm_wday Day of the week. The value range is [0, 6]. 0 means Monday
tm_yday The day of the year, the value range is [1, 366]
tm_isdst Whether it is daylight saving time, the values are 0, 1, - 1

2.2 datetime module

The built-in datetime module in Python provides datetime, date, time and timedelta types. The datetime type contains date and time information. In particular, it should be noted that the objects of these classes are immutable. You need to pass in parameters to create datetime type:

1) datetime

from datetime import datetime, date, time
dt = datetime(2022, 1, 1, 21, 30, 28) # The input parameters are mm / DD / YY, H / min / s respectively
dt
# The result is
datetime.datetime(2022, 1, 1, 21, 30, 28)

For the datetime instance obtained above, you can use its object method to obtain its date, time, year, month and other objects:

dt.time()
# The result is datetime time(21, 30, 28)
dt.date()
# The result is datetime date(2022, 1, 1)
print(dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second)
# The result is 2022 1 21 30 28

2) strftime, strptime functions

The strftime method converts datetime into a string. This method requires you to pass in the string format you want:

dt.strftime('%m/%d/%Y %H:%M')
# The result is
'01/01/2022 21:30'
dt.strftime('%Y-%m-%d %H:%M:%S')
# The result is
'2022-01-01 21:30:28'

The strftime method converts a string to datetime. You need to pass in the string and its corresponding format:

datetime.strptime('20220101213028', '%Y%m%d%H%M%S')
# The result is
datetime.datetime(2022, 1, 1, 21, 30, 28)
datetime.strptime('2022-01-01 21:30:28', '%Y-%m-%d %H:%M:%S')
# The result is
datetime.datetime(2022, 1, 1, 21, 30, 28)

The following table is a complete detailed description of formatting

Datetime format details
type describe
%Y Four digit year
%y Two digit year
%m Two digit month, the value range is [01, 12]
%d Two digit day value, the value range is [01, 31]
%H Hourly value (24-hour system), the value range is [00, 23]
%I Hourly value (12 hour system), value range is [01, 12]
%M Two digit minute value, with a value range of [00, 59]
%S Second value, the value range is [00, 61] (60, 61 are used to distinguish leap seconds)
%w Week value. The value range is [0, 6]. 0 means Sunday
%U The value of the first few weeks of a year, with a value range of [00, 53]; Sunday is the first day of the week, and the week before the first week is week 0
%W The value of the first few weeks of a year, with a value range of [00, 53]; Monday is the first day of the week, and the week before the first Monday is week 0
%z UTC time zone offset, in the format of + HHMM or - HHMM; Null if it is a simple time zone
%F %Abbreviation of Y-%m-%d (e.g. 2022-1-1)
%D %Short for m/%d/%y (e.g. 1 / 1 / 22)

3) datetime.replace

When aggregating or grouping time series data, some values in datatime time series are often replaced, such as replacing minutes and seconds with 0. Datetime is needed at this time The replace() function:

# Specific parameters are as follows
replace(
        year=self.year, 
        month=self.month, 
        day=self.day, 
        hour=self.hour, 
        minute=self.minute, 
        second=self.second, 
        microsecond=self.microsecond, 
        tzinfo=self.tzinfo, 
        * fold=0)

example:

from datetime import datetime, date, time
dt = datetime(2022, 1, 1, 21, 30, 28).replace(minute=0,second=0)
# The result is
datetime.datetime(2022, 1, 1, 21, 0)

4) datetime.timedelta

Two different datetime objects produce a datetime An object of type timedelta that represents the difference between two times:

from datetime import datetime, date, time
dt1 = datetime(2022, 1, 1, 21, 30, 28) # The input parameters are mm / DD / YY, H / min / s respectively
dt2 = datetime(2021, 12, 31, 20, 10, 1) 
delta = dt1 - dt2
delta
# The result is
datetime.timedelta(1, 4827)
# Indicates that the time interval is 1 day and 4827 seconds

Of course, you can also give a datetime Datetime object plus datetime Timedelta to generate a new datetime Datetime object:

dt2 + delta
# The result is
datetime.datetime(2022, 1, 1, 21, 30, 28)

That's all for the date and time. In the next article, I'll introduce tuples in Python data structures!

Keywords: Python Data Analysis

Added by SuprSpy79 on Wed, 05 Jan 2022 08:13:02 +0200