Python timezone package All In One
Python timezone package All In One
中文
日期格式化
Asia/Shanghai
#!/usr/bin/env python3
# coding: utf8
import time
from datetime import datetime, tzinfo, timezone
# import pytz
# ❌ ModuleNotFoundError: No module named 'pytz'
# pip3 install pytz
# tz = pytz.timezone("UTC")
# tz = "zh-cn"
# tz = "Asia/Shanghai"
# ❌ TypeError: tzinfo argument must be None or of a tzinfo subclass, not type 'str'
# ✅
# tz = timezone.utc
# now = datetime.fromtimestamp(time.time(), tz)
now = datetime.fromtimestamp(time.time())
# now = time.time()
print("now time =", now)
# nowTime = time.time()
# ❌ AttributeError: 'float' object has no attribute 'strftime'
# nowTime = int(time.time())
# ❌ AttributeError: 'int' object has no attribute 'strftime'
# nowTime = str(time.time())
# ❌ AttributeError: 'str' object has no attribute 'strftime'
# ✅
nowTime = datetime.now()
# 转换为指定的格式
currentTime = nowTime.strftime("%Y-%m-%d %H:%M:%S")
print("currentTime =", currentTime)
nowTime2 = int(time.time())
timeArray = time.localtime(nowTime2)
# 转换为指定的格式
currentTime2 = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
print("currentTime2 =", currentTime2)
# https://www.cnblogs.com/xgqfrms/p/17309426.html
from datetime import datetime
now = datetime.now()
# 转换为指定的格式
currentTime = now.strftime("%Y-%m-%d %H:%M:%S")
tz / timezone
???
demos
full version solutions
use pip install Python arrow
package
$ pip install -U arrow
https://arrow.readthedocs.io/en/latest/
- use Python
REPL
$ python
>>> import arrow
>>> from datetime import datetime
>>> now = arrow.get(datetime.now(), 'Asia/Shanghai')
>>> print("now =", now)
>>> now = 2023-04-13T00:01:45.222910+08:00
>>> quit()
- run
test.py
as a shell script
$ touch test.py
$ vim ./test.py
$ chmod +x ./test.py
# now = 2023-04-13T00:01:45.222910+08:00
test.py
#!/usr/bin/env python3
# coding: utf8
import arrow
from datetime import datetime
# ✅
now = arrow.get(datetime.now(), 'Asia/Shanghai')
print("now =", now)
# ❌
# arrow.get(datetime.now(), 'zh-cn')
screenshots
(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!
refs
https://www.cnblogs.com/xgqfrms/p/17309426.html#5167310
©xgqfrms 2012-2021
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/17311982.html
未经授权禁止转载,违者必究!