社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

时区:有没有办法在python中用datetime打印GMT(grenwich-time)?

Shakescreen • 4 年前 • 1634 次点击  

到目前为止,代码运行良好。我只是把它作为参考。

import datetime

#prints current local datetime with a time zone of none
dt_today = datetime.datetime.today()
# gives option to introduce a timezone
dt_now = datetime.datetime.now()
# utcnow does not signify a timezone-aware datetime
# instead it offers utc info set to now but tcinfo still set to none
dt_utcnow = datetime.datetime.utcnow()

print(dt_today)

print(dt_now)

print(dt_utcnow)

print(dt_utcnow.strftime('%Y-%m-%d %H:%M:%S.%f %Z'))

我尝试了显而易见的:

dt_gmt = datetime.datetime.gmt()

但那没用。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/133626
文章 [ 2 ]  |  最新文章 4 年前
Shakescreen
Reply   •   1 楼
Shakescreen    5 年前

help(datetime) 导致python库的datetime部分澄清了这一点 gmtime 和 strftime 原来是我要找的:

import time

print("\nGMT: "+time.strftime("%a, %d %b %Y %I:%M:%S %p %Z", time.gmtime())) 
print("Local: "+strftime("%a, %d %b %Y %I:%M:%S %p %Z\n"))
rv.kvetch
Reply   •   2 楼
rv.kvetch    5 年前

而不是 datetime.utcnow() 尝试 datetime.now(timezone.utc) 如中所述 this answer .

下面的例子:

import datetime

#prints current local datetime with a time zone of none
dt_today = datetime.datetime.today()
# gives option to introduce a timezone
dt_now = datetime.datetime.now()
# utcnow does not signify a timezone-aware datetime
# instead it offers utc info set to now but tcinfo still set to none
dt_utcnow = datetime.datetime.now(datetime.timezone.utc)

print(dt_now)

print(dt_utcnow)
print(dt_utcnow.strftime('%Y-%m-%d %H:%M:%S.%f %Z'))

输出:

2021-10-28 19:13:35.069610
2021-10-28 23:13:35.069610+00:00
2021-10-28 23:13:35.069610 UTC

另一种方法是,如果你真的想加入“GMT”,那么:

print(dt_utcnow.isoformat().replace("+00:00", " GMT"))

印刷品: 2021-10-28T23:18:35.637448 GMT