Python3 时间和日期功能:calendar,time,datetime

1. calendar

import calendar
t=calendar.month(2016,2)
print(t,type(t))

#isleap
calendar.isleap(2016)

February 2016
Mo Tu We Th Fr Sa Su
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29
<class ‘str’>
True

2. time

import time
#获取当前操作系统给的时间,返回的是时间戳(float)
time.time()

1545641639.6328876

#localtime() 返回时间元组
t1=time.localtime()
print(t1)
print(type(t1))

time.struct_time(tm_year=2018, tm_mon=12, tm_mday=24, tm_hour=16, tm_min=53, tm_sec=59, tm_wday=0, tm_yday=358, tm_isdst=0)
<class ‘time.struct_time’>

#asctime,ctime 返回字符串
print(time.asctime())
print(type(time.asctime()))

Mon Dec 24 16:53:59 2018
<class ‘str’>

from time import strftime,strptime
t2=strptime("25/12/2018","%d/%m/%Y")
t2

time.struct_time(tm_year=2018, tm_mon=12, tm_mday=25, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=359, tm_isdst=-1)

strftime("%d %b %y",t2)

‘25 Dec 18’

3. datetime

from datetime import datetime
now = datetime.now() #get current time
print(type(now))
print(now)

<class ‘datetime.datetime’>
2018-12-24 16:53:59.699042

delta = datetime(2018,12,25)-datetime(2018,11,25)
print(delta)

print(now+delta)
print(str(now))

delta = datetime(2018,12,25)-datetime(2018,11,25)
print(delta)

print(now+delta)
print(str(now))
1
delta = datetime(2018,12,25)-datetime(2018,11,25)
2
print(delta)
3

4
print(now+delta)
5
print(str(now))
30 days, 0:00:00
2019-01-23 16:53:59.699042
2018-12-24 16:53:59.699042

datetime 和time 都有strftime, strptime

t3=now.strftime('%Y-%m-%d')
t3

‘2018-12-24’

strptime(t3,'%Y-%m-%d')

time.struct_time(tm_year=2018, tm_mon=12, tm_mday=24, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=0, tm_yday=358, tm_isdst=-1)

4. dateutil 自动转义

from dateutil.parser import parse
parse('2018-12-24')

datetime.datetime(2018, 12, 24, 0, 0)

parse('01-01-2018',dayfirst=True)

datetime.datetime(2018, 1, 1, 0, 0)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值