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