python-datetime模块

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'))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值