python 获取当前时间

By 刘志军 , 2020-06-14, 分类: qa

python

python中获取当前时间的几种方式

当前时间

>>> import datetime
>>> now = datetime.datetime.now()
>>> now
datetime.datetime(2020, 6, 14, 10, 14, 57, 780083)

# 转换为字符串格式
>>> now.strftime('%Y-%m-%d %H:%M:%S')
'2020-06-14 10:14:57'
>>>

获取UTC时间

>>> datetime.datetime.utcnow()
datetime.datetime(2020, 6, 14, 2, 18, 38, 484115)

获取某个时区的时间

需要先安装 pytz 库

pip install pytz
>>> import pytz
>>> from datetime import datetime
>>> tz_NY = pytz.timezone('America/New_York') # 纽约时间
>>> datetime.datetime.now(tz_NY)
datetime.datetime(2020, 6, 13, 22, 25, 43, 220083, tzinfo=<DstTzInfo 'America/New_York' EDT-1 day, 20:00:00 DST>)
>>>

关注公众号「Python之禅」,回复「1024」免费获取Python资源

python之禅

猜你喜欢

2015-06-17
如何在Python中正确使用static、class、abstract方法
2020-06-13
python 中 xml 转换为 json
2017-12-26
5个酷毙的Python工具
2020-06-01
最新抖音去水印解析
2017-05-15
一步一步教你认识Python闭包
2022-03-13
从一段小代码开始学习如何重构
2013-10-30
Python“不为人知的”特性
2020-06-04
如何用Python执行linux命令
2020-06-07
python合并两个字典
2019-03-09
30个Python 小例子,帮你快速上手Python