current position:Home>Python date and time library datetime

Python date and time library datetime

2022-09-09 06:50:56Programmer Lao Hua

Article table of contents

datetime : Working with dates and times

calendar : Working with Calendars

time : Access and Transformation of Time

dateutil : Third-Party Libraries for Extended Time Zone and Parsing Support

import timeprint(time.strftime("%Y-%m-%d %H:%M:%S")) # 2020-07-16 13:58:27

Can be as simple as

import datetimeprint(datetime.date.today()) # dateprint(datetime.datetime.now()) # date+time# 2020-07-16# 2020-07-16 13:58:27.161542

Valid types

classDescription
datedate, year, month, day
timetime, hours, minutes, seconds, milliseconds, timezone
datetimedate+time
timedeltaTime Interval
tzinfoTime Zone
timezoneOffset from UTC (Universal Time)

Relationship

objecttimedeltatzinfotimezonetimedatedatetime

Call datetime.weekday() or datetime.isoweekday()

from datetime import datetimeprint(datetime.now().weekday()) # Monday is 0, Sunday is 6print(datetime.now().isoweekday()) # Monday is 1, Sunday is 7

Date offset time

Using the method of datetime.timedeltatotal_seconds() to get how many seconds the time interval contains

Calculate the number of days off for the Spring Festival in 2020

from datetime import date, timedeltadate1 = date(2020, 1, 24) # start holidaydate2 = date(2020, 2, 2+1) # start workdelta = date2 - date1print(delta)print(delta.total_seconds())# 10 days, 0:00:00# 864000.0

Add and subtract time

Using datetime.timedelta

from datetime import datetime, timedeltanow = datetime.now()after_a_week = now + timedelta(days=7)print(now) # 2021-04-15 17:55:58.794208print(after_a_week) # 2021-04-22 17:55:58.794208

String to time

Python 3.7+

from datetime import datetimedate_string = '2021-04-19 18:18:39.458818'print(datetime.fromisoformat(date_string))

Python 3.7 and below

from datetime import datetimedef fromisoformat(date_string):"""datetime string to datetime"""return datetime.strptime(date_string, '%Y-%m-%d %H:%M:%S.%f')date_string = '2021-04-19 18:18:39.458818'print(fromisoformat(date_string))

Time to string (time as filename)

The file name cannot have a colon :

import localeimport datetimelocale.setlocale(locale.LC_CTYPE, 'Chinese') # Set the localeprint(datetime.datetime.now().strftime('%Y/%m/%d'))print(datetime.datetime.now().strftime('%Y year %m month %d day'))print(datetime.datetime.now().strftime('%Y%m%d%H%M%S'))print(datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S_%f'))# 2021/08/20# 20 Aug 2021#20210820141153# 2021-12-15_11-40-27_740240

An error may be reported on Linux: locale.Error: unsupported locale setting

Use this

import datetimenow = datetime.datetime.now()print(now.strftime('%Y{y}%m{m}%d{d}').format(y='year', m='month', d='day'))

Convert with timestamp

import datetimeprint(datetime.datetime(2021, 12, 7).timestamp()) # 1638806400.0print(datetime.datetime.fromtimestamp(1638806400)) # 2021-12-07 00:00:00

copyright notice
author[Programmer Lao Hua],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/252/202209090623380979.html

Random recommended