python datetime模块用法

Posted 心有事焉 勿忘勿助

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python datetime模块用法相关的知识,希望对你有一定的参考价值。

python datetime模块用法

1. 创建naive(无时区信息)的datetime对象

import datetime  
 
dt_utc = datetime.datetime.utcnow()

dt_utc # datetime.datetime(2019, 2, 1, 10, 53, 34, 145034)

dt_utc.tzinfo # None 

dt_local = datetime.datetime.now()

dt_local.tzinfo # None 

# tzinfo为None的datetime对象is naive(不知道怎么翻译好。。。)

# tzinfo为tzinfo对象的None的datetime对象is aware。

# 只有都为naive或者都为aware才可以相互比较

2. 创建的aware(有时区信息)的datetime对象

import datetime  
 
dt_utc = datetime.datetime.utcnow()

dt_utc_aware = dt.replace(tzinfo=datetime.timezone.utc)

dt_utc_aware.tzinfo # datetime.timezone.utc

dt_local = datetime.datetime.now()

dt_local_aware = dt_local.replace(tzinfo=datetime.tzinfo(datetime.timedelta(hours=8)))

3. datetime对象的时区转换

import datetime  
 
dt_utc = datetime.datetime.utcnow()

dt_utc_aware = dt.replace(tzinfo=datetime.timezone.utc)

dt_utc_aware.tzinfo # datetime.timezone.utc

dt_local_aware = dt_utc_aware.astimezone(datetime.timezone(datetime.timedelta(hours=8))) # 转为北京时间

4. datetime对象和时间戳互转

import datetime  
 
import time

stamp = time.time() # 获取时间戳

dt_utc = datetime.datetime.utcfromtimestamp(stamp) # 转为datetime

# datetime.datetime(2019, 2, 1, 12, 52, 59, 268168)

dt_local = datetime.datetime.fromtimestamp(stamp)

# datetime.datetime(2019, 2, 1, 20, 52, 59, 268168)

stp = dt_utc.timestamp() # 转为时间戳,时间戳唯一,不因时区变化

4. datetime对象和date对象互转

import datetime  

d_local = datetime.date.today() # 获取date

dt_utc = datetime.datetime.fromordinal(d_local.toordinal()) # 转为datetime

# datetime.datetime(2019, 2, 1, 0, 0)

d_ = dt_utc.date() # 转为date

# datetime.date(2019, 2, 1)

以上是关于python datetime模块用法的主要内容,如果未能解决你的问题,请参考以下文章

python datetime模块基本用法

python3 日期模块datetime 用法详解

Python中datetime库的用法

Python中的time模块与datetime模块用法总结

Python常用模块:datetime

在命令行中执行python datetime.py就会报找不到内置模块的错误,cannot import name 'datetime'