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

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)

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

Mon Dec 24 16:53:59 2018

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)


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)

你可能感兴趣的:(python)