Home  >  Article  >  Backend Development  >  Summary of usage and common methods of datetime module in Python

Summary of usage and common methods of datetime module in Python

不言
不言Original
2018-09-19 14:56:2320570browse

This article brings you a summary of the usage and common methods of the datetime module in Python. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

The datetime module re-encapsulates the time module to provide more interfaces. The classes provided are:

date, a class representing date

time, a class representing time

datetime, a class representing date and time

timedelta, representing a time interval, that is, the interval between two points in time

tzinfo, information related to time zones

(Objects of these classes are all immutable)

(Classes have class methods, class methods have methods, and methods inherit class methods)

1. Date class

##datetime.date(year, month, day)

Commonly used class methods and attributes:

##date.today()Returns a date object representing the current local time                                                          date.resolutionThe date object represents the smallest unit of date (days)date.fromtimestamp(timestamp)Returns a date object based on the given timestamp

Implementation:

Class method

import datetime
import time
print(datetime.date.max)
print(datetime.date.min)
print(datetime.date.today())
print(datetime.date.resolution)
print(datetime.date.fromtimestamp(time.time()+3600000))      # 给定时间戳的 日期

result

9999-12-31
0001-01-01
2018-09-17
1 day, 0:00:00
2018-10-29

where Commonly used methods and properties:

date.max The maximum value that an object can represent Date (9999-12-31)
date.min The minimum date that the object can represent (0001 -01-01)
The return date is the number of days since 0001-01-01##d.isoweekday()The return date is the day of the week, [1,7], 1 means Monday, 2 means Tuesdayd.isocalendar()Returns a tuple in the format of (year, weekday, isoweekday)d.isoformat()Returns the date string in 'YYYY-MM-DD' formatd.strftime() Custom format string (same as strftime() method of time module)

实现:

方法

print(datetime.date.year)              # <attribute &#39;year&#39; of &#39;datetime.date&#39; objects>
print(datetime.date.today().year)     # 本地时时间的年
print(datetime.date.fromtimestamp(time.time()+3600000).month)   # 给定时间戳的 月
print(datetime.date.today().day)  # 日

print(datetime.date.today().replace(year=2019))
print(datetime.date.today().timetuple())
print(datetime.date.today().toordinal())
print(datetime.date.today().weekday())
print(datetime.date.today().isoweekday())
print(datetime.date.today().isocalendar())
print(datetime.date.today().isoformat())
print(datetime.date.today().strftime(&#39;%Y-%m-%d-%a-%I&#39;))

result

<attribute &#39;year&#39; of &#39;datetime.date&#39; objects>
10
2019-09-17
time.struct_time(tm_year=2018, tm_mon=9, tm_mday=17, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=0, tm_yday=260, tm_isdst=-1)
0
(2018, 38, 1)
2018-09-17
2018-09-17-Mon-12

result

2、time类

其中,time类和time模块各自独立

datetime.time(hour[,minute[,decond[,microsecond[,tzinfo]]]])

常用的类方法与属性:

d.year
d.month month
d.day
##d.replace(year[,month[,day]]) Generate and return a new date object, the original date object remains unchanged                                                                                                       #Return the time tuple (time.struct_time) object corresponding to the date
##d.toordinal()
d .weekday()
The return date is the day of the week, [0,6], 0 means Monday, 1 means Tuesday
time.max 表示的最大时间
time.min                  表示的最小时间
time.resolution 时间的最小单位,这里是1微秒                                                                         

常用的方法与属性:

t.hour
t.minute               
t.second
t.microsecond 微秒
t.tzinfo 时区信息
t.replace() 用参数指定替代(时,分,秒,微秒,时区)对象,生成并返回新的对象
t.isoformat() 返回'HH:MM:SS'格式字符串
t.strftime() 返回自定义格式化字符串

3. Datetime class

is equivalent to combining date and time

datetime.datetime(year,month,day[,hour[,minute[,second[,microsecond[,tzinfo]]]]])

## Commonly used class methods and Properties:

##datetime.maxMaximum datedatetime.minMinimum date##datetime.resolution##datetime.today()datetime.now([tz])datetime.utcnow()datetime.fromtimestamp(timestamp[,tz])datetime.utcfromtimestamp(timestamp)datetime.combine(date, time)datetime.strftime(date_string,format)
The minimum unit of the date represented by the datetime object, 1 microsecond
Return the current local time
Return the current local time Time, if tz is specified, returns the local time in the tz time zone
Returns the current UTC Time
Returns a datetime object based on the given timestamp , if tz is specified, the tz time zone datetime object
according to the timestamp Create a datetime object
Integrate the specified date and time objects For datetime objects
Convert the formatted string to a datetime object

实现:

类方法

import datetime
import time
print(datetime.datetime.resolution)
print(datetime.datetime.today())
print(datetime.datetime.now())
print(datetime.datetime.utcnow())
print(datetime.datetime.fromtimestamp(time.time()))
print(datetime.datetime.utcfromtimestamp(time.time()))
print(datetime.datetime.combine(datetime.date(2019, 3, 5), datetime.time(3, 2, 45)))
print(datetime.datetime.strftime(datetime.date(2019,9,2),&#39;%Y-%m-%d %X&#39;))

result

0:00:00.000001
2018-09-17 20:32:36.868500
2018-09-17 20:32:36.868500
2018-09-17 12:32:36.868500
2018-09-17 20:32:36.868500
2018-09-17 12:32:36.868500
2019-03-05 03:02:45
2019-09-02 00:00:00

其中常用的方法与属性:

##dt.time()Get the time object of dt, tzinfo is none dt.timetz()Get the time object of dt, tzinfo is the same as the tzinfo of datetimedt.replace()Specify parameter replacement (year, month, day, hour, minute, second, subtle , time zone), generate and return a new objectdt.timetuple()Returns the time corresponding to the date and time Tuple (time.struct_time) (excluding tzinfo) dt.utctimetuple()Return UTC time The corresponding time tuple (excluding tzinfo) dt.timestamp()Returns the corresponding dt object Timestampdt.toordinal()The returned date is the first since 0001-01-01 How many days (same as date class)dt.weekday()The day of the week the return date is, [ 1, 7], 1 means Monday (same as date class)dt.isocalendar() Returns a time tuple in the format (year, month, day) (same as date class) ##dt.isoformat()##dt.ctime()

dt.year

dt.month

dt.day

dt.hour

dt.minute

dt.second

dt.microsecond subtle
dt .tzinfo Time zone information
##dt.date() Get the date object of dt
Return a string in the format of 'YYYY-MM-DD HH:MM:SS'
Equivalent to time.ctime of the time module (time.mktime(d.timetuple())) ##dt.strftime ()
Returns the time string in the specified format

实现:

方法

import datetime,time
print(datetime.datetime.today().tzinfo)
print(datetime.datetime.today().date())
print(datetime.datetime.today().time())
print(datetime.datetime.today().timetz())
print(datetime.datetime.today().timetuple())
print(datetime.datetime.today().timestamp())
print(datetime.datetime.today().ctime())

result

None
2018-09-17
20:36:47.560500
20:36:47.560500
time.struct_time(tm_year=2018, tm_mon=9, tm_mday=17, tm_hour=20, tm_min=36, tm_sec=47, tm_wday=0, tm_yday=260, tm_isdst=-1)
1537187807.5605
Mon Sep 17 20:36:47 2018

4、timedelta类

时间加减(代表了两个datetime之间的时间差)

datetime.timedalta(days=0,seconds=0,microseconds=0,milliseconds=0,minutes=0 ,hours=0,weeks=0)

在日期上做天,小时,分钟,秒,毫秒,微秒,周 的时间计算

  • 1毫秒转换为1000微秒

  • 1分钟转换为60秒

  • 1小时转换为3600秒

  • 1周转换为7天

其中,timedelta内部只存储 days,seconds,microseconds

方法与属性:

td.days 天(范围[-999999999,999999999])
td.seconds 秒(范围[0,86399])                                                                                                   
td.microseconds 微秒(范围[0,999999])
td.total_seconds() 以秒为单位返回该时间差

实现:

方法

m = datetime.datetime.now()
print(m)
l = m + datetime.timedelta(3)
print(l)
n = m + datetime.timedelta(hours=4)
print(n)
span = l-m
print(span)
print(span.total_seconds())

result

2018-09-17 16:38:43.021000
2018-09-20 16:38:43.021000
2018-09-17 20:38:43.021000
3 days, 0:00:00
259200.0

5、tzinfo时区类

 其中,tzinfo是一个抽象类,所以不能直接被实例化

 时间转换需要用datetime和pytz来转换时区

The above is the detailed content of Summary of usage and common methods of datetime module in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn