Time tuple and time date in Python

I. time tuple (time.struct_time)

Time tuple is an important type in python. Through time tuple, we can get information such as month, day, hour, minute, second, day of week, day of the year, etc.

Indexes attribute Attribute implication Attribute value
0 tm_year 4-digit year 0000-9999
1 tm_mon month 1-12
2 tm_mday day 1-31
3 tm_hour hour 0-23
4 tm_min Minute 0-59
5 tm_sec second 0-61, 60, 61 are leap seconds
6 tm_wday What day is it 0-6, 0 is Monday
7 tm_yday Day of the year 1 to 366366 leap years
8 tm_isdst Summer marking 1-daylight saving time, 0-non daylight saving time-1-uncertain, possibly because of manual creation

import time

# <class 'time.struct_time'>
localtime = time.localtime()
# time.struct_time(tm_year=2019, tm_mon=11, tm_mday=3, tm_hour=9, tm_min=8, tm_sec=21, tm_wday=0, tm_yday=307, tm_isdst=0)
print(type(localtime))
print(localtime)

for attr in localtime:
    print(attr)

2. Time format

Time format is a very common function, whether it is from string to struct_time, date, datetime, or from struct_time, date, datetime to string.

Formatting mainly involves two functions: str f time: str represents string, f is format, time is time, that is, time is formatted as string str p time: str represents string, p is parse, time is time, that is, string resolution to time

time and datetime have these two functions, which will be introduced later. Let's take a look at the meaning of formatting.

format Meaning
%y Two digit year representation, 00-99
%Y Four digit year representation, 0000-9999
%m Month, 01-12
%d Date, 0-31
%H 24 hour hours, 0-23
%I 12 hour hours, 01-12
%M Minutes, 00-59
%S Seconds, 00-59
%a Local simplified week name
%A Local full week name
%b Local simplified month name
%B Local full month name
%c Local date and time representations
%j Day number, 001-366
%p Local A.M\P.M
%U Week, 00-53, Sunday is the beginning of the week
%W Week, 00-53, Monday is the beginning of the week
%w Day of week, 0-6, Sunday is the beginning of the week
%x Local date
%X Local time
%Z Name of the current time zone
%% %Matches because it is treated as an escape character

Three, time

Time module mainly deals with the format and parsing of struct_time.

On the same day, there are localization time, get timestamp, program sleep and other functions.

Note that unlike datetime.time, datetime.time is the time part of the date time in the general sense, mainly the time, minute and second.

import time

# Greenwich astronomical time tuple
print(time.gmtime())
print(time.gmtime(1577851199))

# Local time tuple
print(time.localtime())
print(time.localtime(1577851199))

# Format time
# time.asctime([tupletime])
print(time.asctime())

# time.ctime([secs])
print(time.ctime())

# Format to 2020-01-01 11:59:59
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))

# Convert format string to timestamp
a = "2020-01-01 11:59:59"
str2TT = time.strptime(a, "%Y-%m-%d %H:%M:%S")

# Tuple to timestamp
ts = time.mktime(str2TT)
print(ts)

# time stamp
print(time.time())
# Dormant seconds
time.sleep(1)

IV. datetime

The datetime module mainly uses: datetime.date: date (2025-01-01) datetime.time: time (12:00:00) datetime.datetime: period (2025-01-01 12:00:00)

import datetime
import time

today = datetime.date.today()
print(today)
print(type(today))

# Day of the week, isoweekday Sunday is the first day, weekday Monday is the first day
print(today.isoweekday())
print(today.weekday())
# time tuples
print(today.timetuple())
# The next few days
print(today.toordinal())
datetime.date.fromordinal(today.toordinal())

print(datetime.date(2020, 1, 1))
datetime.date.fromtimestamp(time.time())

print(datetime.time(12, 59, 59, 999))

# Current local date
print(datetime.datetime.now())
# Current utc date
print(datetime.datetime.utcnow())
print(datetime.datetime(2020, 1, 31, 12, 59, 59, 0))

# String to date
print(datetime.datetime.strptime('2020-1-1 12:01', '%Y-%m-%d %H:%M'))
# Date format
print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M'))

The most common ones are:

# String get date
datetime.datetime.strptime('2020-1-1 12:01', '%Y-%m-%d %H:%M')
# Date format
datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')

V. timedelta

timedelta is also under the datetime module, which is mainly used for date calculation.

It is very useful when you need to use the time interval. For example, you need a date like last month, previous day, last week, which can be easily obtained by using datetime and timedelta.

import datetime
import time

today = datetime.date.today()
# Last day of last month
lastMonthLastDay = datetime.date(today.year, today.month, 1) - datetime.timedelta(1)
print(lastMonthLastDay)
# First day of last month
lastMonthFirstDay = datetime.date(lastMonthLastDay.year, lastMonthLastDay.month, 1)
print(lastMonthFirstDay)

# A week ago
print(today - datetime.timedelta(7))

# This Monday
thisMonday = today - datetime.timedelta(today.isoweekday()-1)
print(thisMonday)
# This Sunday
lastMonday = thisMonday - datetime.timedelta(7)
print(lastMonday)

# Last Sunday
lastSunday = today - datetime.timedelta(days=today.isoweekday())
print(lastSunday)
# Last Monday
lastMonday = lastSunday - datetime.timedelta(days=6)
print(lastMonday)

# 8 hours later
print(datetime.datetime.now() + datetime.timedelta(hours=8))

start = datetime.datetime.now()
time.sleep(1)
end = datetime.datetime.now()
diff = end - start
# <class 'datetime.timedelta'>
print(type(diff))
print(diff)

Vi. calendar

import calendar
# Leap year or not
print(calendar.isleap(2020))

Calendar is a calendar

Tags: Programming Attribute Python

Posted on Mon, 04 Nov 2019 20:02:59 -0500 by We Must Design