datetime模块
导入from datetime import datetime
import time
import calendar模块
1.自己创建 一个 当前时间对象
nowtime = datetime.today()
print(nowtime)
2.创建一个 指定日期
s_time = datetime(2019,10,1,8,0,0)
print(s_time)
print(type( s_time ) )
3.其他
import time
print( time.time() )
print( datetime.fromtimestamp( time.time()))
timestr = '2019/10/1 08:00:00'
print( datetime.strptime(timestr,'%Y/%m/%d %H:%M:%S'))
datetime 对象 可以通过 属性 直接 获取 年月日时分秒的数值
print( nowtime.year )
print( nowtime.month )
print( nowtime.day )
print( nowtime.hour )
print( nowtime.minute )
print( nowtime.second )
print( nowtime.microsecond )
我们经常 将 年月日一起说, 时分秒 一起说
返回年月日
print( nowtime.date() )
返回时分秒
print( nowtime.time() )
import calendar
print(calendar.month(2020,1))
还可以 直接 获取 周几
nowtime.weekday() 是从 0 开始 算 周一
print( nowtime.weekday())
nowtime.weekday() 是从 1 开始 算 周一
print( nowtime.isoweekday())
格式化显示 datetime
先创建一个
time2 = 1558932300
datetime_obj = datetime.fromtimestamp(time2)
print(datetime_obj)
print(datetime_obj.timestamp())
datetime_obj.strftime()
print( datetime_obj.strftime('%Y//%m//%d %H:%M:%S %a') )
我们还可以格式化时 加入其它描述语句
print(datetime_obj.strftime('time : %Y-%m-%d %H:%M:%S') )
还有一种 格式化 的方式 ,由 datetime
print( datetime.strftime(datetime_obj,'%Y-%m-%d %H:%M:%S') )
如果你的字符串 转 时间对象中有中文 ,依然复制再更改
timestr2 = '北京时间: 2019/10/1 08:08:00'
print( datetime.strptime(timestr2,'北京时间: %Y/%m/%d %H:%M:%S'))