带有示例的Python datetime模块

Python中的datetime模块 (datetime Module in Python)

Date and time manipulation in Python is done using a module named datetime. It has classes that have functions to work on a date, time, timezone, and time differences. It is an inbuilt module so it does not have to be installed exclusively.

Python中的日期和时间操作是使用名为datetime的模块完成的。 它具有可处理日期,时间,时区和时差的函数的类。 它是一个内置模块,因此不必专门安装。

datetime module not only enables us to do the date and time calculations, but it also is helpful in output formatting via efficient attribute extraction.

datetime模块不仅使我们能够进行日期和时间计算,而且还有助于通过有效的属性提取进行输出格式化。

A.日期和时间对象 (A. Date and time objects)

datetime library involves working with date and time, which are objects in Python. Date and time objects can be categorized as "aware" or "naive".

datetime库涉及使用日期和时间,这是Python中的对象。 日期和时间对象可以分类为“ aware”“ naive”

Aware Object: An aware object contains time as well as the timezone information. An aware object can distinguish itself from other aware objects as here we know the exact time of the two objects at an instance. Classes datetime and time provide objects which may be aware or naive.

感知对象 :感知对象包含时间以及时区信息。 一个有意识的对象可以将自己与其他有意识的对象区分开来,因为在这里我们知道两个对象在一个实例上的确切时间。 日期时间和时间类提供的对象可能是已知的或幼稚的。

How to check if an object is naive or aware?

如何检查一个对象是否幼稚或知道?

A datetime or time object (x) is aware only when,

日期 时间或时间对象( x )仅在以下情况下知道:

  • x.tzinfo is not none

    x.tzinfo不是无

  • x.tzinfo.utcoffset(x) does not return none

    x.tzinfo.utcoffset(x)不返回无

Naive Object: A naive object only contains time information. It does not have timezone information. Whether a naive object is representing Coordinated Universal Time (UTC), local time, or time in some other timezone is completely dependent on the program. It can not distinguish itself from other naive objects as the timezone info is missing. Classes date provides naive objects in Python.

天真的对象 :天真的对象仅包含时间信息。 它没有时区信息。 天真的对象是表示协调世界时(UTC),本地时间还是其他时区中的时间,完全取决于程序。 由于缺少时区信息,因此无法将其与其他幼稚对象区分开。 Classs date提供Python中的幼稚对象。

B.日期时间常数 (B. Constants in datetime)

This module contains two constants:

该模块包含两个常量:

  1. MINYEAR: It is the smallest valid year number for a date or datetime object. Its value is 1.

    MINYEAR :这是日期日期时间对象的最小有效年份。 其值为1。

  2. MAXYEAR: It is the largest valid year number for a date or datetime object. Its value is 9999.

    MAXYEAR :这是日期日期时间对象的最大有效年份。 其值为9999。

C.日期时间的课程 (C. Classes in datetime)

There are six classes available in this module which allow manipulation of date and time:

此模块中有六个可用的类,它们允许操纵日期和时间:

1.日期类 (1. date class)

An object of this class represents a date(format: year, month, day) in a calendar. The calendar used for the format is currently the Gregorian calendar.

此类的对象表示日历中的日期(格式: year , month , day )。 该格式使用的日历当前是公历。

The constructor of this class requires all three parameters: year, month, and day.

此类的构造函数需要所有三个参数: year , month和day 。

Syntax:

句法:

    class datetime.date(year, month, day)

The arguments should be in the following range –

参数应在以下范围内–

    MINYEAR <= year <= MAXYEAR
    1 <= month <= 12
    1 <= day <= number of days in the given month and year

If the value of the arguments is outside the above range, a ValueError is pointed out and if the type is not an integer, then a TypeError is raised.

如果参数的值超出上述范围,则指出ValueError ,如果类型不是整数,则引发TypeError

Example:

例:

from datetime import date 
 
date0 = date(2001, 10, 27) 
print("Sample date example", date0)

Output

输出量

    Sample date example 2001-10-27

类方法 (Class Methods)

date class has the following class methods and attributes:

date类具有以下类方法和属性:

FunctionUse
today()Returns the current local date
fromtimestamp(timestamp)Return the local date corresponding to the POSIX timestamp
fromordinal(ordinal)Returns the date corresponding with Gregorian ordinal, in which 01-01-01 has ordinal 1
Range: 1 <= ordinal <= date.max.toordinal()
fromisoformat(date_string)Returns a date corresponding to a date_string given in the format YYYY-MM-DD
Available from version 3.7
fromisocalendar(year, week, day)Return a date corresponding to the ISO calendar date specified by year, week and day
Available from version 3.8
功能
今天() 返回当前本地日期
fromtimestamp(时间戳) 返回与POSIX时间戳相对应的本地日期
fromordinal(普通) 返回与公历序号相对应的日期,其中01-01-01的序号为1
范围:1 <=序数<= date.max.toordinal()
fromisoformat(日期字符串) 返回对应于格式为YYYY-MM-DD的date_string的日期
从3.7版开始可用
fromisocalendar(年,周,日) 返回与年,周和日指定的ISO日历日期相对应的日期
从3.8版本开始可用
类属性 (Class Attributes)
AttributeMeaningValue
date.minIt is the smallest representable date.(MINYEAR,1,1)or(1,1,1)
date.maxIt is the largest representable date(MAXYEAR,12,31) or(9999,12,31)
date.resolutionIt is the smallest possible difference between non-equal date objectstimedelta(days=1)
属性 含义
date.min 这是最小的可表示日期。 (MINYEAR,1,1)或(1,1,1)
date.max 这是最大的可代表日期 (MAXYEAR,12,31)或(9999,12,31)
日期解析 这是非相等日期对象之间的最小差异 timedelta(天数= 1)

Example:

例:

## Python program explaining the 
## use of date class methods

from datetime import date
import time

## today() function
datetoday= date.today()
print("Today's date is", datetoday) 

## fromtimestamp() function
date1 = date.fromtimestamp(time.time())
print("Date on the given timestamp is ", date1)

## fromordinal() function
ordinal0= date.fromordinal(1000)
print("Date on 1000 ordinal was", ordinal0)

## fromisoformat() function
dateiso= date.fromisoformat('2019-12-04')
print("Date in string is", dateiso)

## fromisocalendar(year,week,day) function
ii = date.fromisocalendar(2010,4,3)
print("Date on corresponding week, day and year was", ii)

Output

输出量

Today's date is 2020-04-28
Date on the given timestamp is  2020-04-28
Date on 1000 ordinal was 0003-09-27
Date in string is 2019-12-04
Date on corresponding week, day and year was 2010-01-27

实例方法 (Instance methods)

An instance method is a method that uses an instance of a class, while the class method can be used just with the class name. Given below are the instance methods of date class:

实例方法是使用类实例的方法,而类方法只能与类名一起使用。 下面是date类的实例方法:

MethodUse
replace(year=self.year, month=self.month, day=self.day)Replaces the date with the arguments given in the braces, the arguments missing have the same initial value
timetuple()Return a time.struct_time.
toordinal()Return the proleptic Gregorian ordinal of the date, where January 1 of year 1 has ordinal 1
weekday()Return the day of the week as an integer, where Monday is 0 and Sunday is 6
isoweekday()Return the day of the week as an integer in ISO 8601 format, where Monday is 1 and Sunday is 7
isocalendar()Return a 3-tuple, (ISO year, ISO week number, ISO weekday)
isoformat()Return a string representing the date in ISO 8601 format, YYYY-MM-DD
__str()__Same as isoformat
ctime()Return a string representing the date
strftime(format)Return a string representing the date, controlled by an explicit format string
__format__(format)Same as strftime
方法
replace(year = self.year,month = self.month,day = self.day) 用大括号中给出的参数替换日期,缺少的参数具有相同的初始值
timetuple() 返回一个time.struct_time。
toordinal() 返回年份的公历序号,其中1年的1月1日具有序数1
工作日() 以整数形式返回星期几,其中星期一为0,星期日为6
isoweekday() 以ISO 8601格式返回星期几作为整数,其中星期一为1,星期日为7
isocalendar() 返回一个三元组(ISO年,ISO周号,ISO工作日)
isoformat() 以ISO 8601格式返回代表日期的字符串,YYYY-MM-DD
__str()__ 与isoformat相同
ctime() 返回代表日期的字符串
strftime(格式) 返回表示日期的字符串,由明确的格式字符串控制
__format __(格式) 与strftime相同

Example:

例:

## Python program explaining the 
## use of date class instance methods

from datetime import date

## replace() function
x = date(2019, 9, 25)
x.replace(year=2010, day=15)
print("The date after replacing is", x)

## timetuple function
t = x.timetuple()
## returns a time.struct_time which is an object containing date and time details 
print ("Timetuple of the above date is", t)

## toordinal() function
d = x.toordinal()
print("The Gregorian ordinal number of the given date is", d)

## weekday() function
print("The weekday of the date",x, "is", x.weekday())

## isoweekday() function
print("The weekday of the date",x, "in ISO calendar is", x.isoweekday())

## isocalendar() function
print("A date in Gregorian calendar",x,"will be",x.isocalendar(),"in isocalendar")

## Below Functions convert date to string

## isoformat function
s=x.isoformat()
print("The date string of x in ISO 8601 format is", s)

## str function
print("The date string of x =", str(x))

## ctime() function
print("The complete string representation of date",x,"is", x.ctime())

## strftime() function
xyear =  x.strftime("%Y")
xdate_time = x.strftime("%Y/%m/%d, %H:%M:%S")
print("Date to string using format codes")
print(xyear)
print(xdate_time)

## format() function
st=format(x)
print("Date string =",st)

Output

输出量

The date after replacing is 2019-09-25
Timetuple of the above date is time.struct_time(tm_year=2019, tm_mon=9, tm_mday=25, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=2, tm_yday=268, tm_isdst=-1)
The Gregorian ordinal number of the given date is 737327
The weekday of the date 2019-09-25 is 2
The weekday of the date 2019-09-25 in ISO calendar is 3
A date in Gregorian calendar 2019-09-25 will be (2019, 39, 3) in isocalendar
The date string of x in ISO 8601 format is 2019-09-25
The date string of x = 2019-09-25
The complete string representation of date 2019-09-25 is Wed Sep 25 00:00:00 2019
Date to string using format codes
2019
2019/09/25, 00:00:00
Date string = 2019-09-25

2.时间课 (2. Time Class)

An object of time class represents the local time of day, which may be adjusted via a tzinfo object. If the tzinfo is None, the time object is naive else it is aware.

时间类的对象表示一天中的本地时间,可以通过tzinfo对象进行调整。 如果tzinfo为None,则时间对象是幼稚的,否则它会知道。

Syntax:

句法:

    class datetime.time(hour, minute, second, microsecond, tzinfo, *, fold)

Arguments are optional in the syntax, tzinfo can be None, otherwise it is an instance of tzinfo subclass. Other arguments have the following ranges:

参数在语法中是可选的, tzinfo可以为None,否则它是tzinfo子类的实例。 其他参数的范围如下:

    0 <= hour < 24,
    0 <= minute < 60
    0 <= second < 60
    0 <= microsecond < 1000000
    fold in [0, 1]

The arguments should be in the given ranges otherwise a ValueError is raised.

参数应在给定范围内,否则会引发ValueError 。

Example:

例:

from datetime import time
 
time0 = time(13, 24,34) 
print("Sample time object example", time0)

Output

输出量

Sample time object example 13:24:34

类属性 (Class Attributes)

Time class has the following class attributes:

时间类具有以下类属性:

AttributeMeaningValue
time.minIt is the smallest representable time.time(0, 0, 0, 0)
time.maxIt is the largest representable time.time(23, 59, 59, 999999)
time.resolutionIt is the smallest possible difference between non-equal time objects.timedelta(microseconds=1)
属性 含义
时间 这是最小的可表示时间。 时间(0,0,0,0)
最大时间 这是最大的可表示时间。 时间(23,59,59,999999)
时间分辨率 这是非相等时间对象之间可能的最小差异。 timedelta(微秒= 1)
实例方法 (Instance Methods)

Most of the methods are the same as date Class. time class has following functions which use time object instances:

大多数方法与日期类相同。 时间类具有以下使用时间对象实例的函数:

MethodsUse
replace(hour=self.hour, minute=self.minute, second=self.second, microsecond=self.microsecond, tzinfo=self.tzinfo, * fold=0)Replaces the time with the arguments given in the braces, the arguments missing have the same initial value
isoformat(timespec='auto')Return a string representing the time in ISO 8601 format
__str__()Returns a string of the given time object
strftime(format)Return a string representing the time, controlled by an explicit format string.
__format__(format)Same as strftime(format)
utcoffset()Returns offset of local time from UTC, as a timedelta object
dst()Return the daylight saving time (DST) adjustment, as a timedelta object or None if DST information isn't known
tzname()Returns the time zone name of the time object passed as a string
方法
替换(hour = self.hour,minutes = self.minute,second = self.second,microsecond = self.microsecond,tzinfo = self.tzinfo,* fold = 0) 用括号中的参数替换时间,缺少的参数具有相同的初始值
isoformat(timespec ='auto') 以ISO 8601格式返回代表时间的字符串
__str __() 返回给定时间对象的字符串
strftime(格式) 返回表示时间的字符串,由明确的格式字符串控制。
__format __(格式) 与strftime(format)相同
utcoffset() 返回本地时间相对于UTC的偏移量,作为timedelta对象
dst() 返回夏令时(DST)调整,作为timedelta对象;如果不知道DST信息,则返回None。
tzname() 返回以字符串形式传递的时间对象的时区名称

3. datetime类 (3. datetime Class)

This class contains information on both time and date. As a date object, it assumes the Gregorian Calendar extended in both directions, and as a time object, it assumes there are 360*24 seconds every day.

此类包含有关时间和日期的信息。 作为日期对象,它假定公历在两个方向上都延伸;作为时间对象,它假定每天有360 * 24秒。

Constructor Syntax:

构造函数语法:

    class datetime.datetime(
        year, 
        month, 
        day, 
        hour=0, 
        minute=0, 
        second=0, 
        microsecond=0, 
        tzinfo=None, 
        *, 
        fold=0)

Argument range and limitation similar to date and time objects.

参数范围和限制类似于日期和时间对象。

Example:

例:

from datetime import datetime
 
datetime0 = datetime(2020, 12, 1, 13, 2, 34) 
print("Sample datetime object example", datetime0)

datetime1 = datetime.now()
print("Date and time right now", datetime1)

Output

输出量

Sample datetime object example 2020-12-01 13:02:34
Date and time right now 2020-04-28 21:02:47.521826

类的方法和属性 (Class Methods and Attributes)

Class methods and attributes in datetime class are:

datetime类中的类方法和属性为:

类方法 (Class Methods)
MethodUse
today()Returns the current local datetime, with no timezone information
now()Returns the current local date and time
utcnow()Return the current UTC date and time, with tzinfo None
fromtimestamp(timestamp, tz=None)Returns the local date and time corresponding to the POSIX timestamp
utcfromtimestamp(timestamp)Return the UTC datetime corresponding to the POSIX timestamp, with tzinfo None
fromordinal(ordinal)Returns the datetime corresponding with the proleptic Gregorian ordinal
combine(date, time, tzinfo=self.tzinfo)Return a new datetime object whose date components are equal to the given date object’s and time components are equal to the given time object’s
fromisoformat(date_string)Return a datetime corresponding to a date_string
fromisocalendar(year, week, day)Returns a datetime corresponding to the ISO calendar date specified by year, week and day.
strptime(date_string, format)Return a datetime for the given date_string, parsed according to the given format.
方法
今天() 返回当前本地日期时间,不带时区信息
现在() 返回当前本地日期和时间
utcnow() 使用tzinfo返回当前UTC日期和时间无
fromtimestamp(timestamp,tz = None) 返回与POSIX时间戳相对应的本地日期和时间
utcfromtimestamp(时间戳) 使用tzinfo返回与POSIX时间戳相对应的UTC日期时间
fromordinal(普通) 返回与多义的格里高利序号相对应的日期时间
合并(日期,时间,tzinfo = self.tzinfo) 返回一个新的datetime对象,其日期分量等于给定的日期对象,而时间分量等于给定的时间对象。
fromisoformat(日期字符串) 返回对应于date_string的datetime
fromisocalendar(年,周,日) 返回对应于由年,周和日指定的ISO日历日期的日期时间。
strptime(date_string,格式) 返回给定date_string的日期时间,并根据给定格式进行解析。
类属性 (Class Attributes)
AttributesUseValue
datetime.minIt is the earliest representable datetimedatetime(MINYEAR, 1, 1, tzinfo=None)
datetime.maxIt is the last representable datetimedatetime(MAXYEAR, 12, 31, 23, 59, 59, 999999, tzinfo=None)
datetime.resolutionIt is the smallest possible difference between non-equal datetime objectstimedelta(microseconds=1)
属性
datetime.min 这是最早的可表示日期时间 datetime(MINYEAR,1,1,tzinfo = None)
datetime.max 这是最后一个可表示的日期时间 datetime(MAXYEAR,12,31,23,59,59,999999,tzinfo = None)
日期时间分辨率 这是非相等日期时间对象之间可能的最小差异 timedelta(微秒= 1)

Example:

例:

## Python program explaining the 
## use of datetime class methods

from datetime import datetime
import time

## today() function
datetoday = datetime.today()
print("Today's date:", datetoday)

## now() function
datetodaywithtime = datetime.now()
print("Today's date with time:", datetodaywithtime)

## utcnow() function
datetimeutc = datetime.utcnow()
print("Current corresponding UTC time and date", datetimeutc)

## fromtimestamp(timestamp, tz=None) function
x1 = datetime.fromtimestamp(time.time())
print(x1)

## utcfromtimestamp(timestamp)
x2 = datetime.utcfromtimestamp(time.time())
print(x2)

##fromordinal(ordinal)
print("Date on ordinal 100000", datetime.fromordinal(100000))

##strptime(date_string, format)
print("Date string:", datetime.strptime("04 May, 2020" ,"%d %B, %Y"))

##fromisoformat(date_string)
st =  datetime.fromisoformat(str(datetoday))
print("Date string of the object:", st)


##fromisocalendar(year, week, day)
print("Date on year 2019, 7th week and 4th day in isocalendar was:", datetime.fromisocalendar(2019, 7, 4))

Output

输出量

Today's date: 2020-04-28 21:07:46.878993
Today's date with time: 2020-04-28 21:07:46.879494
Current corresponding UTC time and date 2020-04-28 21:07:46.879529
2020-04-28 21:07:46.879543
2020-04-28 21:07:46.879556
Date on ordinal 100000 0274-10-16 00:00:00
Date string: 2020-05-04 00:00:00
Date string of the object: 2020-04-28 21:07:46.878993
Date on year 2019, 7th week and 4th day in isocalendar was: 2019-02-14 00:00:00

实例属性 (Instance Attributes)
AttributesValue
datetime.yearMINYEAR <= year
datetime.month1 <= month <= 12
datetime.day1 <= day <= Number of days in that month of that year
datetime.hourrange(24)
datetime.minuterange(60)
datetime.secondrange(60)
datetime.microsecondrange(1000000)
datetime.tzinfoObject passed as tzinfo argument in object declaration, None if none was passed
datetime.foldIn [0,1]
Available from version 3.6
属性
datetime.year MINYEAR <=年
datetime.month 1 <=月<= 12
datetime.day 1 <=天<=该年那个月的天数
datetime.hour 范围(24)
datetime.minute 范围(60)
datetime.second 范围(60)
datetime.microsecond 范围(1000000)
datetime.tzinfo 对象作为对象声明中的tzinfo参数传递,如果没有传递则为None
datetime.fold 在[0,1]
从版本3.6开始可用
实例方法 (Instance Methods)

Instance methods include many methods same as in date and time class:

实例方法包括许多与日期和时间类相同的方法:

MethodUse
date()Returns date object with same year, month and day
time()Return time object with same hour, minute, second, microsecond and fold. tzinfo is None.
timetz()Return times object with same hour, minute, second, microsecond, fold, and tzinfo attributes.
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)Replaces the datetime with the arguments given in the braces, the arguments missing have the same initial value
astimezone(tz=None)Return a datetime object with new tzinfo attribute tz
utcoffset(dt)Returns offset of local time from UTC, as a timedelta object
dst()Return the daylight saving time (DST) adjustment, as a timedelta object or None if DST information isn’t known
tzname()Returns the time zone name of the datetime object passed as a string
timetuple()Return a time.struct_time such as returned by date.timetuple()
utctimetuple()If datetime instance d is naive, it is same as timetuple() except that tm_isdst is forced to 0 regardless of what d.dst() returns.
toordinal()Returns the proleptic Gregorian ordinal of the given date
timestamp()Returns POSIX timestamp corresponding to the given date
weekday()Returns the day of the week as an integer, where Monday is 0 and Sunday is 6
isoweekday()Returns the day of the week as an integer, where Monday is 1 and Sunday is 7
isocalendar()Returns a 3-tuple, (ISO year, ISO week number, ISO weekday)
isoformat()Return a string containing date and time in ISO 8601 format
__str__()String representation of the given datetime
ctime()Same as str
strftime()Returns a string representing the date and time, controlled by an explicit format string.
__format__()Same as strftime()
方法
日期() 返回具有相同年份,月份和日期的日期对象
时间() 返回具有相同小时,分钟,秒,微秒和倍数的时间对象。 tzinfo为“无”。
timetz() 返回时间对象具有相同的小时,分​​钟,秒,微秒,倍数和tzinfo属性。
替换 (year = self.year,month = self.month,day = self.day,hour = self.hour,minute = self.minute,second = self.second,microsecond = self.microsecond,tzinfo = self.tzinfo, *折== 0) 用大括号中给出的参数替换日期时间,缺少的参数具有相同的初始值
astimezone(tz =无) 返回具有新的tzinfo属性tz的datetime对象
utcoffset(dt) 返回本地时间相对于UTC的偏移量,作为timedelta对象
dst() 返回夏令时(DST)调整,作为timedelta对象;如果不知道DST信息,则返回None。
tzname() 返回以字符串形式传递的datetime对象的时区名称
timetuple() 返回一个time.struct_time,例如date.timetuple()返回的
utctimetuple() 如果datetime实例d是天真的,则它与timetuple()相同,只是无论d.dst()返回什么,都将tm_isdst强制设置为0。
toordinal() 返回给定日期的公历格里高利序数
timestamp() 返回与给定日期相对应的POSIX时间戳
工作日() 以整数形式返回星期几,其中星期一为0,星期日为6
isoweekday() 以整数形式返回星期几,其中星期一为1,星期日为7
isocalendar() 返回一个三元组(ISO年,ISO周号,ISO工作日)
isoformat() 返回包含日期和时间的ISO 8601格式的字符串
__str __() 给定日期时间的字符串表示形式
ctime() 与str相同
strftime() 返回表示日期和时间的字符串,由明确的格式字符串控制。
__格式__() 与strftime()相同

4. timedelta类 (4. timedelta Class)

An object of timedelta class represents the value of the difference between two dates or times.

timedelta类的对象表示两个日期或时间之间的差值。

Syntax:

句法:

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

类属性 (Class Attributes)
AttributeMeaningValue
timedelta.minIt is the most negative timedelta objecttimedelta(-999999999)
timedelta.maxIt is the most positive timedelta objecttimedelta(days=999999999, hours=23, minutes=59, seconds=59, microseconds=999999)
timedelta.resolutionIt is the smallest possible difference between non-equal timedelta objectstimedelta(microseconds=1)
属性 含义
时间增量 它是最负的timedelta对象 timedelta(-999999999)
最大时间增量 它是最积极的timedelta对象 timedelta(天= 999999999,小时= 23,分钟= 59,秒= 59,微秒= 999999)
时间增量解析 这是非相等时间增量对象之间的最小差异 timedelta(微秒= 1)
实例属性 (Instance Attributes)
AttributesRange
daysBetween -999999999 and 999999999 inclusive
secondBetween 0 and 86399 inclusive
millisecondBetween 0 and 999999 inclusive
属性 范围
-999999999和999999999之间(含)
第二 0至86399(含)之间
毫秒 0至999999(含)之间
实例方法 (Instance Method)

timedelta class has one instance method: total_seconds() which returns the total number of seconds covered in the given duration.

timedelta类具有一个实例方法: total_seconds() ,该方法返回给定持续时间内覆盖的总秒数。

Example:

例:

## Python program to illustrate 
## the use of timedelta class
from datetime import datetime, timedelta  
    
presentdate = datetime.now()  
print ("Present date:", str(presentdate))  
    
## Date and time after 4 years
date1 = presentdate + timedelta(days = (4*365))  
print ("Date after 4 years from now", str(date1))  
    
# Date and time after 4 years 2 months 3 hours from now  
date2 = presentdate + timedelta(days = (4*365+2*30), hours=3)   
print ("Date after 4 years 2 months 3 hours from now", str(date2))

## total_seconds function
total = timedelta(minutes = 2*15).total_seconds()
print("Total seconds in 30 minutes:", total)

Output

输出量

Present date: 2020-04-28 21:19:25.932396
Date after 4 years from now 2024-04-27 21:19:25.932396
Date after 4 years 2 months 3 hours from now 2024-06-27 00:19:25.932396
Total seconds in 30 minutes: 1800.0

5. tzinfo类 (5. tzinfo class)

tzinfo is an abstract base class, ie, it cannot be instantiated directly. A concrete subclass has to derive it and implement the methods provided by this abstract class.

tzinfo是一个抽象基类,即不能直接实例化。 一个具体的子类必须派生它并实现此抽象类提供的方法。

We had learnt about the aware objects that when the instance of the tzinfo class(not None) is passed to the constructors of the datetime and time objects, they become aware objects. It helps in the conversion of local time to UTC or account for daylight saving time.

我们已经了解了感知对象,当tzinfo类的实例(不是None)的实例传递给datetime和time对象的构造函数时 ,它们成为感知对象。 它有助于将本地时间转换为UTC或考虑夏令时。

方法 (Methods)
MethodUse
utcoffset(dt)Returns offset of local time from UTC, as a timedelta object
dst(dt)Returns the daylight saving time (DST) adjustment, as a timedelta object or None if DST information isn’t known
tzname(dt)Returns the time zone name of the datetime object passed as a string
fromutc(dt)Returns the equivalent local time corresponding to the date and time of the object in UTC
方法
utcoffset(dt) 返回本地时间相对于UTC的偏移量,作为timedelta对象
dst(dt) 返回夏令时(DST)调整,作为timedelta对象;如果不知道DST信息,则返回None。
tzname(dt) 返回以字符串形式传递的datetime对象的时区名称
fromutc(dt) 返回与UTC中对象的日期和时间相对应的等效本地时间

Example:

例:

from datetime import datetime
import pytz

naive= datetime.now()
## Tzinfo is missing from the time object which is naive 
print(naive)
print(naive.tzinfo)
timezone = pytz.timezone("Europe/Berlin")
aware = timezone.localize(naive)

## After adding the timezone info, the object it becomes aware
print(aware)
print(aware.tzinfo)

Output

输出量

2020-04-29 14:32:13.640369
None
2020-04-29 14:32:13.640369+02:00
Europe/Berlin

6.时区类 (6. timezone Class)

The timezone class is a subclass of tzinfo. Every instance of this class represents a timezone defined by a fixed offset from UTC.

时区类是tzinfo的子类。 此类的每个实例都代表一个时区,该时区由与UTC的固定偏移量定义。

Syntax:

句法:

    class datetime.timezone(offset, name=None)

The offset argument must be specified as a timedelta object representing the difference between the local time and UTC.

必须将offset参数指定为代表本地时间与UTC之间的时差的timedelta对象。

Range of the offset:

偏移范围:

    -timedelta(hours=24) <= offset <= timedelta(hours=24)

If the offset is east of UTC, then it is considered positive and if it is west of UTC, it is negative. Since there are 24 hours in a day, -timedelta(24) and timedelta(24) are the largest values possible.

如果偏移量在UTC以东,则视为正值;如果偏移量在UTC以西,则为负值。 由于一天中有24小时,因此-timedelta(24)和timedelta(24)是可能的最大值。

方法 (Methods)

Since it is a subclass of tzinfo, the methods of this class are the same as tzinfo.

由于它是tzinfo的子类,因此此类的方法与tzinfo相同。

Reference: datetime — Basic date and time types

参考: datetime-基本日期和时间类型

翻译自: https://www.includehelp.com/python/datetime-module-with-examples.aspx

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值