python时间类型_datetime --- 基本的日期和时间类型 — Python 3.8.1 文档

A datetime object is a single object containing all the information

from a date object and a time object.

Like a date object, datetime assumes the current Gregorian

calendar extended in both directions; like a time object,

datetime assumes there are exactly 3600*24 seconds in every day.

构造器 :

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

The year, month and day arguments are required. tzinfo may be None, or an

instance of a tzinfo subclass. The remaining arguments must be integers

in the following ranges:

MINYEAR <= year <= MAXYEAR,

1 <= month <= 12,

1 <= day <= 指定年月的天数,

0 <= hour < 24,

0 <= minute < 60,

0 <= second < 60,

0 <= microsecond < 1000000,

fold in [0, 1].

如果参数不在这些范围内,则抛出 ValueError 异常。

3.6 新版功能:增加了 fold 参数。

其它构造器,所有的类方法:

classmethoddatetime.today()¶

Return the current local datetime, with tzinfo None.

等价于:

datetime.fromtimestamp(time.time())

This method is functionally equivalent to now(), but without a

tz parameter.

classmethoddatetime.now(tz=None)¶

Return the current local date and time.

If optional argument tz is None

or not specified, this is like today(), but, if possible, supplies more

precision than can be gotten from going through a time.time() timestamp

(for example, this may be possible on platforms supplying the C

gettimeofday() function).

If tz is not None, it must be an instance of a tzinfo subclass,

and the current date and time are converted to tz’s time zone.

This function is preferred over today() and utcnow().

classmethoddatetime.utcnow()¶

Return the current UTC date and time, with tzinfo None.

This is like now(), but returns the current UTC date and time, as a naive

datetime object. An aware current UTC datetime can be obtained by

calling datetime.now(timezone.utc). See also now().

警告

Because naive datetime objects are treated by many datetime methods

as local times, it is preferred to use aware datetimes to represent times

in UTC. As such, the recommended way to create an object representing the

current time in UTC is by calling datetime.now(timezone.utc).

classmethoddatetime.fromtimestamp(timestamp, tz=None)¶

返回对应于 POSIX 时间戳例如 time.time() 的返回值的本地日期和时间。 如果可选参数 tz 为 None 或未指定,时间戳会被转换为所在平台的本地日期和时间,返回的 datetime 对象将为天真型。

If tz is not None, it must be an instance of a tzinfo subclass, and the

timestamp is converted to tz’s time zone.

fromtimestamp() may raise OverflowError, if the timestamp is out of

the range of values supported by the platform C localtime() or

gmtime() functions, and OSError on localtime() or

gmtime() failure.

It's common for this to be restricted to years in

1970 through 2038. Note that on non-POSIX systems that include leap seconds in

their notion of a timestamp, leap seconds are ignored by fromtimestamp(),

and then it's possible to have two timestamps differing by a second that yield

identical datetime objects. This method is preferred over

utcfromtimestamp().

在 3.3 版更改:引发 OverflowError 而不是 ValueError,如果时间戳数值超出所在平台 C localtime() 或 gmtime() 函数的支持范围的话。 并会在 localtime() 或 gmtime() 出错时引发 OSError 而不是 ValueError。

在 3.6 版更改:fromtimestamp() 可能返回 fold 值设为 1 的实例。

classmethoddatetime.utcfromtimestamp(timestamp)¶

Return the UTC datetime corresponding to the POSIX timestamp, with

tzinfo None. (The resulting object is naive.)

This may raise OverflowError, if the timestamp is

out of the range of values supported by the platform C gmtime() function,

and OSError on gmtime() failure.

It's common for this to be restricted to years in 1970 through 2038.

datetime.fromtimestamp(timestamp, timezone.utc)

在 POSIX 兼容的平台上,它等价于以下表达式:

datetime(1970, 1, 1, tzinfo=timezone.utc) + timedelta(seconds=timestamp)

不同之处在于后一种形式总是支持完整年份范围:从 MINYEAR 到 MAXYEAR 的开区间。

警告

Because naive datetime objects are treated by many datetime methods

as local times, it is preferred to use aware datetimes to represent times

in UTC. As such, the recommended way to create an object representing a

specific timestamp in UTC is by calling

datetime.fromtimestamp(timestamp, tz=timezone.utc).

在 3.3 版更改:引发 OverflowError 而不是 ValueError,如果时间戳数值超出所在平台 C gmtime() 函数的支持范围的话。 并会在 gmtime() 出错时引发 OSError 而不是 ValueError。

classmethoddatetime.fromordinal(ordinal)¶

Return the datetime corresponding to the proleptic Gregorian ordinal,

where January 1 of year 1 has ordinal 1. ValueError is raised unless 1

<= ordinal <= datetime.max.toordinal(). The hour, minute, second and

microsecond of the result are all 0, and tzinfo is None.

classmethoddatetime.combine(date, time, tzinfo=self.tzinfo)¶

Return a new datetime object whose date components are equal to the

given date object's, and whose time components

are equal to the given time object's. If the tzinfo

argument is provided, its value is used to set the tzinfo attribute

of the result, otherwise the tzinfo attribute of the time argument

is used.

For any datetime object d,

d == datetime.combine(d.date(), d.time(), d.tzinfo). If date is a

datetime object, its time components and tzinfo attributes

are ignored.

在 3.6 版更改:增加了 tzinfo 参数。

classmethoddatetime.fromisoformat(date_string)¶

Return a datetime corresponding to a date_string in one of the

formats emitted by date.isoformat() and datetime.isoformat().

Specifically, this function supports strings in the format:

YYYY-MM-DD[*HH[:MM[:SS[.fff[fff]]]][+HH:MM[:SS[.ffffff]]]]

where * can match any single character.

警告

This does not support parsing arbitrary ISO 8601 strings - it is only intended

as the inverse operation of datetime.isoformat(). A more full-featured

ISO 8601 parser, dateutil.parser.isoparse is available in the third-party package

dateutil.

This does not support parsing arbitrary ISO 8601 strings - it is only intended

as the inverse operation of datetime.isoformat().

示例:

>>>from datetime import datetime

>>>datetime.fromisoformat('2011-11-04')

datetime.datetime(2011, 11, 4, 0, 0)

>>>datetime.fromisoformat('2011-11-04T00:05:23')

datetime.datetime(2011, 11, 4, 0, 5, 23)

>>>datetime.fromisoformat('2011-11-04 00:05:23.283')

datetime.datetime(2011, 11, 4, 0, 5, 23, 283000)

>>>datetime.fromisoformat('2011-11-04 00:05:23.283+00:00')

datetime.datetime(2011, 11, 4, 0, 5, 23, 283000, tzinfo=datetime.timezone.utc)

>>>datetime.fromisoformat('2011-11-04T00:05:23+04:00')

datetime.datetime(2011, 11, 4, 0, 5, 23,

tzinfo=datetime.timezone(datetime.timedelta(seconds=14400)))

3.7 新版功能.

classmethoddatetime.fromisocalendar(year, week, day)¶

Return a datetime corresponding to the ISO calendar date specified

by year, week and day. The non-date components of the datetime are populated

with their normal default values. This is the inverse of the function

datetime.isocalendar().

3.8 新版功能.

classmethoddatetime.strptime(date_string, format)¶

Return a datetime corresponding to date_string, parsed according to

format.

这相当于:

datetime(*(time.strptime(date_string, format)[0:6]))

ValueError is raised if the date_string and format

can't be parsed by time.strptime() or if it returns a value which isn't a

time tuple. For a complete list of formatting directives, see

strftime() 和 strptime() 的行为.

类属性:

datetime.min¶

最早的可表示 datetime,datetime(MINYEAR, 1, 1, tzinfo=None)。

datetime.max¶

最晚的可表示 datetime,datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999, tzinfo=None)。

datetime.resolution¶

两个不相等的 datetime 对象之间可能的最小间隔,timedelta(microseconds=1)。

实例属性(只读):

datetime.year¶

datetime.month¶

1 至 12(含)

datetime.day¶

返回1到指定年月的天数间的数字。

datetime.hour¶

取值范围是 range(24)。

datetime.minute¶

取值范围是 range(60)。

datetime.second¶

取值范围是 range(60)。

datetime.microsecond¶

取值范围是 range(1000000)。

datetime.tzinfo¶

作为 tzinfo 参数被传给 datetime 构造器的对象,如果没有传入值则为 None。

datetime.fold¶

In [0, 1]. Used to disambiguate wall times during a repeated interval. (A

repeated interval occurs when clocks are rolled back at the end of daylight saving

time or when the UTC offset for the current zone is decreased for political reasons.)

The value 0 (1) represents the earlier (later) of the two moments with the same wall

time representation.

3.6 新版功能.

支持的运算:

运算

结果

datetime2 = datetime1 + timedelta

(1)

datetime2 = datetime1 - timedelta

(2)

timedelta = datetime1 - datetime2

(3)

datetime1 < datetime2

datetime2 is a duration of timedelta removed from datetime1, moving forward in

time if timedelta.days > 0, or backward if timedelta.days < 0. The

result has the same tzinfo attribute as the input datetime, and

datetime2 - datetime1 == timedelta after. OverflowError is raised if

datetime2.year would be smaller than MINYEAR or larger than

MAXYEAR. Note that no time zone adjustments are done even if the

input is an aware object.

计算 datetime2 使得 datetime2 + timedelta == datetime1。 与相加操作一样,结果具有与输入的 datetime 相同的 tzinfo 属性,即使输入的是一个感知型对象,该方法也不会进行时区调整。

Subtraction of a datetime from a datetime is defined only if

both operands are naive, or if both are aware. If one is aware and the other is

naive, TypeError is raised.

If both are naive, or both are aware and have the same tzinfo attribute,

the tzinfo attributes are ignored, and the result is a timedelta

object t such that datetime2 + t == datetime1. No time zone adjustments

are done in this case.

If both are aware and have different tzinfo attributes, a-b acts

as if a and b were first converted to naive UTC datetimes first. The

result is (a.replace(tzinfo=None) - a.utcoffset()) - (b.replace(tzinfo=None)

- b.utcoffset()) except that the implementation never overflows.

当 datetime1 的时间在 datetime2 之前则认为 datetime1 小于 datetime2。

If one comparand is naive and the other is aware, TypeError

is raised if an order comparison is attempted. For equality

comparisons, naive instances are never equal to aware instances.

If both comparands are aware, and have the same tzinfo attribute, the

common tzinfo attribute is ignored and the base datetimes are

compared. If both comparands are aware and have different tzinfo

attributes, the comparands are first adjusted by subtracting their UTC

offsets (obtained from self.utcoffset()).

在 3.3 版更改:Equality comparisons between aware and naive datetime

instances don't raise TypeError.

注解

In order to stop comparison from falling back to the default scheme of comparing

object addresses, datetime comparison normally raises TypeError if the

other comparand isn't also a datetime object. However,

NotImplemented is returned instead if the other comparand has a

timetuple() attribute. This hook gives other kinds of date objects a

chance at implementing mixed-type comparison. If not, when a datetime

object is compared to an object of a different type, TypeError is raised

unless the comparison is == or !=. The latter cases return

False or True, respectively.

实例方法:

datetime.date()¶

返回具有同样 year, month 和 day 值的 date 对象。

datetime.time()¶

Return time object with same hour, minute, second, microsecond and fold.

tzinfo is None. See also method timetz().

在 3.6 版更改:fold 值会被复制给返回的 time 对象。

datetime.timetz()¶

Return time object with same hour, minute, second, microsecond, fold, and

tzinfo attributes. See also method time().

在 3.6 版更改:fold 值会被复制给返回的 time 对象。

datetime.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)¶

Return a datetime with the same attributes, except for those attributes given

new values by whichever keyword arguments are specified. Note that

tzinfo=None can be specified to create a naive datetime from an aware

datetime with no conversion of date and time data.

3.6 新版功能:增加了 fold 参数。

datetime.astimezone(tz=None)¶

返回一个具有新的 tzinfo 属性 tz 的 datetime 对象,并会调整日期和时间数据使得结果对应的 UTC 时间与 self 相同,但为 tz 时区的本地时间。

If provided, tz must be an instance of a tzinfo subclass, and its

utcoffset() and dst() methods must not return None. If self

is naive, it is presumed to represent time in the system timezone.

If called without arguments (or with tz=None) the system local

timezone is assumed for the target timezone. The .tzinfo attribute of the converted

datetime instance will be set to an instance of timezone

with the zone name and offset obtained from the OS.

如果 self.tzinfo 为 tz,self.astimezone(tz) 等于 self: 不会对日期或时间数据进行调整。 否则结果为 tz 时区的本地时间,代表的 UTC 时间与 self 相同:在 astz = dt.astimezone(tz) 之后,astz - astz.utcoffset() 将具有与 dt - dt.utcoffset() 相同的日期和时间数据。

If you merely want to attach a time zone object tz to a datetime dt without

adjustment of date and time data, use dt.replace(tzinfo=tz). If you

merely want to remove the time zone object from an aware datetime dt without

conversion of date and time data, use dt.replace(tzinfo=None).

请注意默认的 tzinfo.fromutc() 方法在 tzinfo 的子类中可以被重载,从而影响 astimezone() 的返回结果。 如果忽略出错的情况,astimezone() 的行为就类似于:

def astimezone(self, tz):

if self.tzinfo is tz:

return self

# Convert self to UTC, and attach the new time zone object.

utc = (self - self.utcoffset()).replace(tzinfo=tz)

# Convert from UTC to tz's local time.

return tz.fromutc(utc)

在 3.3 版更改:tz 现在可以被省略。

在 3.6 版更改:astimezone() 方法可以由无知型实例调用,这将假定其表示本地时间。

datetime.utcoffset()¶

如果 tzinfo 为 None,则返回 None,否则返回 self.tzinfo.utcoffset(self),并且在后者不返回 None 或者一个幅度小于一天的 timedelta 对象时将引发异常。

在 3.7 版更改:UTC 时差不再限制为一个整数分钟值。

datetime.dst()¶

如果 tzinfo 为 None,则返回 None,否则返回 self.tzinfo.dst(self),并且在后者不返回 None 或者一个幅度小于一天的 timedelta 对象时将引发异常。

在 3.7 版更改:DST 差值不再限制为一个整数分钟值。

datetime.tzname()¶

如果 tzinfo 为 None,则返回 None,否则返回 self.tzinfo.tzname(self),如果后者不返回 None 或者一个字符串对象则将引发异常。

datetime.timetuple()¶

d.timetuple() is equivalent to:

time.struct_time((d.year, d.month, d.day,

d.hour, d.minute, d.second,

d.weekday(), yday, dst))

where yday = d.toordinal() - date(d.year, 1, 1).toordinal() + 1

is the day number within the current year starting with 1 for January

1st. The tm_isdst flag of the result is set according to the

dst() method: tzinfo is None or dst() returns

None, tm_isdst is set to -1; else if dst() returns a

non-zero value, tm_isdst is set to 1; else tm_isdst is

set to 0.

datetime.utctimetuple()¶

If datetime instance d is naive, this is the same as

d.timetuple() except that tm_isdst is forced to 0 regardless of what

d.dst() returns. DST is never in effect for a UTC time.

If d is aware, d is normalized to UTC time, by subtracting

d.utcoffset(), and a time.struct_time for the

normalized time is returned. tm_isdst is forced to 0. Note

that an OverflowError may be raised if d.year was

MINYEAR or MAXYEAR and UTC adjustment spills over a year

boundary.

警告

Because naive datetime objects are treated by many datetime methods

as local times, it is preferred to use aware datetimes to represent times

in UTC; as a result, using utcfromtimetuple may give misleading

results. If you have a naive datetime representing UTC, use

datetime.replace(tzinfo=timezone.utc) to make it aware, at which point

you can use datetime.timetuple().

datetime.toordinal()¶

Return the proleptic Gregorian ordinal of the date. The same as

self.date().toordinal().

datetime.timestamp()¶

Return POSIX timestamp corresponding to the datetime

instance. The return value is a float similar to that

returned by time.time().

Naive datetime instances are assumed to represent local

time and this method relies on the platform C mktime()

function to perform the conversion. Since datetime

supports wider range of values than mktime() on many

platforms, this method may raise OverflowError for times far

in the past or far in the future.

对于感知型 datetime 实例,返回值的计算方式为:

(dt - datetime(1970, 1, 1, tzinfo=timezone.utc)).total_seconds()

3.3 新版功能.

在 3.6 版更改:timestamp() 方法使用 fold 属性来消除重复间隔中的时间歧义。

注解

There is no method to obtain the POSIX timestamp directly from a

naive datetime instance representing UTC time. If your

application uses this convention and your system timezone is not

set to UTC, you can obtain the POSIX timestamp by supplying

tzinfo=timezone.utc:

timestamp = dt.replace(tzinfo=timezone.utc).timestamp()

或者通过直接计算时间戳:

timestamp = (dt - datetime(1970, 1, 1)) / timedelta(seconds=1)

datetime.weekday()¶

返回一个整数代表星期几,星期一为 0,星期天为 6。 相当于 self.date().weekday()。 另请参阅 isoweekday()。

datetime.isoweekday()¶

返回一个整数代表星期几,星期一为 1,星期天为 7。 相当于 self.date().isoweekday()。 另请参阅 weekday(), isocalendar()。

datetime.isocalendar()¶

Return a 3-tuple, (ISO year, ISO week number, ISO weekday). The same as

self.date().isocalendar().

datetime.isoformat(sep='T', timespec='auto')¶

Return a string representing the date and time in ISO 8601 format:

YYYY-MM-DDTHH:MM:SS.ffffff, if microsecond is not 0

YYYY-MM-DDTHH:MM:SS, if microsecond is 0

If utcoffset() does not return None, a string is

appended, giving the UTC offset:

YYYY-MM-DDTHH:MM:SS.ffffff+HH:MM[:SS[.ffffff]], if microsecond

is not 0

YYYY-MM-DDTHH:MM:SS+HH:MM[:SS[.ffffff]], if microsecond is 0

示例:

>>>from datetime import datetime, timezone

>>>datetime(2019, 5, 18, 15, 17, 8, 132263).isoformat()

'2019-05-18T15:17:08.132263'

>>>datetime(2019, 5, 18, 15, 17, tzinfo=timezone.utc).isoformat()

'2019-05-18T15:17:00+00:00'

The optional argument sep (default 'T') is a one-character separator,

placed between the date and time portions of the result. For example:

>>>from datetime import tzinfo, timedelta, datetime

>>>class TZ(tzinfo):

... """A time zone with an arbitrary, constant -06:39 offset."""

... def utcoffset(self, dt):

... return timedelta(hours=-6, minutes=-39)

...

>>>datetime(2002, 12, 25, tzinfo=TZ()).isoformat(' ')

'2002-12-25 00:00:00-06:39'

>>>datetime(2009, 11, 27, microsecond=100, tzinfo=TZ()).isoformat()

'2009-11-27T00:00:00.000100-06:39'

可选参数 timespec 要包含的额外时间组件值 (默认为 'auto')。它可以是以下值之一:

'auto': 如果 microsecond 为 0 则与 'seconds' 相同,否则与 'microseconds' 相同。

'hours': Include the hour in the two-digit HH format.

'minutes': Include hour and minute in HH:MM format.

'seconds': Include hour, minute, and second

in HH:MM:SS format.

'milliseconds': Include full time, but truncate fractional second

part to milliseconds. HH:MM:SS.sss format.

'microseconds': Include full time in HH:MM:SS.ffffff format.

注解

排除掉的时间部分将被截断,而不是被舍入。

ValueError will be raised on an invalid timespec argument:

>>>from datetime import datetime

>>>datetime.now().isoformat(timespec='minutes')

'2002-12-25T00:00'

>>>dt = datetime(2015, 1, 1, 12, 30, 59, 0)

>>>dt.isoformat(timespec='microseconds')

'2015-01-01T12:30:59.000000'

3.6 新版功能:增加了 timespec 参数。

datetime.__str__()¶

对于 datetime 实例 d,str(d) 等价于 d.isoformat(' ')。

datetime.ctime()¶

Return a string representing the date and time:

>>>from datetime import datetime

>>>datetime(2002, 12, 4, 20, 30, 40).ctime()

'Wed Dec 4 20:30:40 2002'

The output string will not include time zone information, regardless

of whether the input is aware or naive.

d.ctime() 等效于:

time.ctime(time.mktime(d.timetuple()))

on platforms where the native C ctime() function

(which time.ctime() invokes, but which

datetime.ctime() does not invoke) conforms to the C standard.

datetime.strftime(format)¶

Return a string representing the date and time, controlled by an explicit format

string. For a complete list of formatting directives, see

strftime() 和 strptime() 的行为.

datetime.__format__(format)¶

Same as datetime.strftime(). This makes it possible to specify a format

string for a datetime object in formatted string

literals and when using str.format(). For a

complete list of formatting directives, see

strftime() 和 strptime() 的行为.

Examples of Usage: datetime¶

Examples of working with datetime objects:

>>>from datetime import datetime, date, time, timezone

>>># Using datetime.combine()

>>>d = date(2005, 7, 14)

>>>t = time(12, 30)

>>>datetime.combine(d, t)

datetime.datetime(2005, 7, 14, 12, 30)

>>># Using datetime.now()

>>>datetime.now()

datetime.datetime(2007, 12, 6, 16, 29, 43, 79043) # GMT +1

>>>datetime.now(timezone.utc)

datetime.datetime(2007, 12, 6, 15, 29, 43, 79060, tzinfo=datetime.timezone.utc)

>>># Using datetime.strptime()

>>>dt = datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M")

>>>dt

datetime.datetime(2006, 11, 21, 16, 30)

>>># Using datetime.timetuple() to get tuple of all attributes

>>>tt = dt.timetuple()

>>>for it in tt:

... print(it)

...

2006 # year

11 # month

21 # day

16 # hour

30 # minute

0 # second

1 # weekday (0 = Monday)

325 # number of days since 1st January

-1 # dst - method tzinfo.dst() returned None

>>># Date in ISO format

>>>ic = dt.isocalendar()

>>>for it in ic:

... print(it)

...

2006 # ISO year

47 # ISO week

2 # ISO weekday

>>># Formatting a datetime

>>>dt.strftime("%A,%d. %B %Y %I:%M%p")

'Tuesday, 21. November 2006 04:30PM'

>>>'The{1}is {0:%d}, the{2}is {0:%B}, the{3}is {0:%I:%M%p}.'.format(dt, "day", "month", "time")

'The day is 21, the month is November, the time is 04:30PM.'

The example below defines a tzinfo subclass capturing time zone

information for Kabul, Afghanistan, which used +4 UTC until 1945

and then +4:30 UTC thereafter:

from datetime import timedelta, datetime, tzinfo, timezone

class KabulTz(tzinfo):

# Kabul used +4 until 1945, when they moved to +4:30

UTC_MOVE_DATE = datetime(1944, 12, 31, 20, tzinfo=timezone.utc)

def utcoffset(self, dt):

if dt.year < 1945:

return timedelta(hours=4)

elif (1945, 1, 1, 0, 0) <= dt.timetuple()[:5] < (1945, 1, 1, 0, 30):

# An ambiguous ("imaginary") half-hour range representing

# a 'fold' in time due to the shift from +4 to +4:30.

# If dt falls in the imaginary range, use fold to decide how

# to resolve. See PEP495.

return timedelta(hours=4, minutes=(30 if dt.fold else 0))

else:

return timedelta(hours=4, minutes=30)

def fromutc(self, dt):

# Follow same validations as in datetime.tzinfo

if not isinstance(dt, datetime):

raise TypeError("fromutc() requires a datetime argument")

if dt.tzinfo is not self:

raise ValueError("dt.tzinfo is not self")

# A custom implementation is required for fromutc as

# the input to this function is a datetime with utc values

# but with a tzinfo set to self.

# See datetime.astimezone or fromtimestamp.

if dt.replace(tzinfo=timezone.utc) >= self.UTC_MOVE_DATE:

return dt + timedelta(hours=4, minutes=30)

else:

return dt + timedelta(hours=4)

def dst(self, dt):

# Kabul does not observe daylight saving time.

return timedelta(0)

def tzname(self, dt):

if dt >= self.UTC_MOVE_DATE:

return "+04:30"

return "+04"

Usage of KabulTz from above:

>>>tz1 = KabulTz()

>>># Datetime before the change

>>>dt1 = datetime(1900, 11, 21, 16, 30, tzinfo=tz1)

>>>print(dt1.utcoffset())

4:00:00

>>># Datetime after the change

>>>dt2 = datetime(2006, 6, 14, 13, 0, tzinfo=tz1)

>>>print(dt2.utcoffset())

4:30:00

>>># Convert datetime to another time zone

>>>dt3 = dt2.astimezone(timezone.utc)

>>>dt3

datetime.datetime(2006, 6, 14, 8, 30, tzinfo=datetime.timezone.utc)

>>>dt2

datetime.datetime(2006, 6, 14, 13, 0, tzinfo=KabulTz())

>>>dt2 == dt3

True

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值