Python datetime astimezone()方法与示例

Python datetime.astimezone()方法 (Python datetime.astimezone() Method)

datetime.astimezone() method is used to manipulate objects of datetime class of module datetime.

datetime.astimezone()方法用于操作模块datetime的datetime类的对象。

It uses an instance of the class and returns a datetime object with new tzinfo attribute tz. It works on a datetime class instance.

它使用该类的实例,并返回具有新tzinfo属性tzdatetime对象。 它适用于datetime类实例。

Module:

模块:

    import datetime

Class:

类:

    from datetime import datetime

Syntax:

句法:

    astimezone(tz)

Parameter(s):

参数:

  • tz - timezone information which should be changed.

    tz-应更改的时区信息。

Return value:

返回值:

Returns a datetime object with new tzinfo attribute tz.

返回具有新的tzinfo属性tz的日期时间对象。

Example:

例:

from datetime import datetime
import pytz

naive= datetime.now()
## Tzinfo is missing from the time object 
## which is naive 
print("Tzinfo:",naive.tzinfo)
print()

## Adding a timezone
timezone = pytz.timezone("Asia/Kolkata")
aware1 = naive.astimezone(timezone)
print("Tzinfo:",aware1.tzinfo)
print()

## After adding the timezone info, 
## the object it becomes aware
timezone = pytz.timezone("Asia/Tokyo")
aware2 = aware1.astimezone(timezone)
print("Initial tzinfo:",aware1.tzinfo)
print("Final tzinfo:",aware2.tzinfo)
print()

## No timezone was defined for naive
print(naive)
## Timezone changed from None to Asia/Kolkata 
## for aware1 object
print(aware1)
## Timezone changed from Asia/Kolkata to 
## Asia/Tokyo for aware2 object
print(aware2)

Output

输出量

Tzinfo: None

Tzinfo: Asia/Kolkata

Initial tzinfo: Asia/Kolkata
Final tzinfo: Asia/Tokyo

2020-04-30 18:44:12.784666
2020-05-01 00:14:12.784666+05:30
2020-05-01 03:44:12.784666+09:00


翻译自: https://www.includehelp.com/python/datetime-astimezone-method-with-example.aspx

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值