Python datetime tzname()方法与示例

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

datetime.tzname() method is used in the datetime class of module datetime.

datetime.tzname()方法在模块datetime的datetime类中使用。

It uses an instance of the class and returns the time zone name of the datetime object passed, as a string. It is an instance method and works on an aware object. For a naive object, it returns None.

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

Module:

模块:

    import datetime

Class:

类:

    from datetime import datetime

Syntax:

句法:

    tzname()

Parameter(s):

参数:

  • None

    没有

Return value:

返回值:

Returns the time zone name of the datetime object passed, as a string.

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

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)
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())

Output

输出量

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


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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值