当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Python datetime tzname()用法及代码示例


Python datetime.tzname() 方法

datetime.tzname() 方法用于 datetime 模块的 datetime 类。

它使用类的实例并以字符串形式返回传递的日期时间对象的时区名称。它是一个实例方法,适用于感知对象。对于一个简单的对象,它返回 None。

模块:

    import datetime

类:

    from datetime import datetime

用法:

    tzname()

参数:

  • None

返回值:

以字符串形式返回传递的日期时间对象的时区名称。

例:

from datetime import datetime
import pytz

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

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

## After adding the timezone info, 
## the object it becomes aware
timezone = pytz.timezone("Asia/Tokyo")
aware2 = timezone.localize(naive)
print("Tzinfo:",aware2.tzinfo)
print("Timezone name:", aware2.tzname())
print()

timezone = pytz.timezone("America/New_York")
aware3 = timezone.localize(naive)
print("Tzinfo:",aware3.tzinfo)
## timedelta comes as -1 day 20 hrs 
## which is equal to -4 hrs 
print("Timezone name:", aware3.tzname())
print()

## You can also use the astimezone function
## of  datetime to 
timezone = pytz.timezone("Europe/Berlin")
aware4 = naive.astimezone(timezone)
print("Tzinfo:",aware4.tzinfo)
print("Timezone name:", aware4.tzname())

输出

2020-04-30 20:20:30.748312
None
Timezone for a naive object:None

2020-04-30 20:20:30.748312+05:30
Tzinfo:Asia/Kolkata
Timezone name:IST

Tzinfo:Asia/Tokyo
Timezone name:JST

Tzinfo:America/New_York
Timezone name:EDT

Tzinfo:Europe/Berlin
Timezone name:CEST


相关用法


注:本文由纯净天空筛选整理自 Python datetime tzname() Method with Example。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。