datetime和time获取当前日期和时间

目录

datetime获取当前日期和时间

time获取当前日期和时间


datetime获取当前日期和时间

import datetime
import time
 
# 获取当前时间, 其中中包含了year, month, hour, 需要import datetime
today = datetime.date.today()
print(today)
print(today.year)
print(today.month)
print(today.day)
'''
>>>2017-01-01
>>>2017
>>>1
>>>1
'''
 
 
# 获得明天, 其他依次类推
tomorrow = today + datetime.timedelta(days=1)
print(tomorrow)
'''
>>>2017-01-02
'''
 
 
# 时间相减,相加同理
now = datetime.timedelta(days=0, hours=0, minutes=3, seconds=50);
pre = datetime.timedelta(days=0, hours=0, minutes=1, seconds=10);
 
duration_sec = (now - pre).seconds
duration_day = (now - pre).days
print(type(duration_sec))
print(type(now - pre))
print(duration_sec)
print(duration_day)
'''
>>>
>>>
>>>160
>>>0
'''

 
# 使用datetime.now()
now = datetime.datetime.now()
print(now)
print(now.year)
print(now.month)
print(now.day)
print(now.hour)
print(now.minute)
print(now.second)
print(now.microsecond)
'''
>>>2017-01-01 23:49:34.789292
>>>2017
>>>1
>>>1
>>>23
>>>49
>>>34
>>>789292
'''

time获取当前日期和时间

import time
 
# 使用time.strftime(format, p_tuple)获取当前时间,需要import time
now = time.strftime("%H:%M:%S")
print(now)
'''
>>>23:49:34
'''
# time.strftime(format, p_tuple)返回的是格式化的日期字符串。如果要使用.hour这类函数,要先转化为日期格式
today = datetime.datetime.strptime(time.strftime('%Y-%m-%d %H:%M:%S'), format)
print(today)
yestoday=today-datetime.timedelta(days=1,hours=today.hour,minutes=today.minute,seconds=today.second) 
print(yestoday)

'''
>>>2019-11-27 10:18:22
>>>2019-11-26 00:00:00
'''

 

你可能感兴趣的:(Python相关,python,time,datetime,当前日期时间)