Python timezone package All In One

Posted xgqfrms

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python timezone package All In One相关的知识,希望对你有一定的参考价值。

Python timezone package All In One Python arrow package 日期格式化 Asia/Shanghai

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/

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

  1. 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

(

python - packages

  • packages(包)的概念,可以解决不同的插件模块的重名问题
  • 在一个目录中,通过创建__init__.py文件来定义这个目录里面包含着packages, 这个文件可以是一个空文件,也可以用来设置__all__变量
  • 几种导入package的方式
  • import ***
  • from *** import ***
  • from *** import *
  • 包内子模块之间的引用,可以使用绝对路径引用,也可以使用相对路径引用
  • 一个包有多个目录,使用__path__变量来设置,一般都用不上。

reference:
https://docs.python.org/3/tutorial/modules.html#tut-packages

以上是关于Python timezone package All In One的主要内容,如果未能解决你的问题,请参考以下文章

Python 时间处理---------笔记

python datetime时区转换

python常用内建模块

python timezone.py

python 将App添加到Project并更新Timezone

为啥 python datetime replace timezone 返回不同的时区?