Python时区:获取缩写和UTC偏移量 [英] Python Time zone: get abbreviation and UTC offset
本文介绍了Python时区:获取缩写和UTC偏移量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
谢谢
解决方案
假设您有日期和时间可用(请参阅我的评论),最简单的方法可能是 strftime
:
从dateutil导入datetime
import tz
时区= tz.gettz(澳大利亚/墨尔本)
dt = datetime.now(时区)
print(f''{dt.strftime('%Z')}(GMT {dt.strftime('%z')})''))
#AEST(GMT + 1000)
如果您确实想获得指定的输出,我想您必须稍微复杂一点:
total_minutes,秒= divmod(dt.utcoffset()。total_seconds(),60)
小时,分钟= divmod(total_minutes,60)
utcoff = f {int(hours):+ d}:{int(minutes):02d}如果是分钟,则f {int(hours):+ d}
print(f''{dt.strftime('%Z')}(GMT {utcoff})''))
#AEST(GMT + 10)
my time zone is "Australia/Melbourne" (I have multiple zones like this when I give this to my function) and I need the output like this ASET(GMT +10). How can I reach my answer?
Thank you
解决方案
assuming you have date and time available (see my comment), the easiest way is probably strftime
:
from datetime import datetime
from dateutil import tz
timezone = tz.gettz("Australia/Melbourne")
dt = datetime.now(timezone)
print(f"{dt.strftime('%Z')}(GMT{dt.strftime('%z')})")
# AEST(GMT+1000)
If you exactly want to get the specified output, I suppose you have to go a little more sophisticated:
total_minutes, seconds = divmod(dt.utcoffset().total_seconds(), 60)
hours, minutes = divmod(total_minutes, 60)
utcoff = f"{int(hours):+d}:{int(minutes):02d}" if minutes else f"{int(hours):+d}"
print(f"{dt.strftime('%Z')}(GMT{utcoff})")
# AEST(GMT+10)
这篇关于Python时区:获取缩写和UTC偏移量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文