import time
#time
a=time.time()
print("Seconds since epoch :",a,end='n----------n')
#ctime
print("Current date and time:")
print(time.ctime(a),end='n----------n') #Tue Oct 18 15:13:16 2022
#localtime
print("Local time :")
print(time.localtime(a),end='n----------n') #time.struct_time(tm_year=2022, tm_mon=10, tm_mday=18, tm_hour=15, tm_min=13, tm_sec=16, tm_wday=1, tm_yday=291, tm_isdst=0
#gmtime(UTC format)
print("Local time in UTC format :")
print(time.gmtime(a),end='n-----------n') #time.struct_time(tm_year=2022, tm_mon=10, tm_mday=18, tm_hour=7, tm_min=13, tm_sec=16, tm_wday=1, tm_yday=291, tm_isdst=0)
#strftime
c = time.localtime() # get struct_time
d = time.strftime("%m/%d/%Y, %H:%M:%S", c)
print("String representing date and time:")
print(d,end='n----------n') #10/18/2022, 15:13:17n----------ntime.strptime parses string and returns it in struct_time format :n
#strptime
print("time.strptime parses string and returns it in struct_time format :n")
e = "06 AUGUST, 2019"
f = time.strptime(e, "%d %B, %Y")
print(f) #time.struct_time(tm_year=2019, tm_mon=8, tm_mday=6, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=218, tm_isdst=-1)
###########################################################################################
###########################################################################################
import datetime
#datetime constructor
print("Datetime constructor:n")
print(datetime.datetime(2019,5,3,8,45,30,234),end='n----------n') #2019-05-03 08:45:30.000234
#today
print("The current date and time using today :n")
print(datetime.datetime.today(),end='n----------n') #2022-10-18 15:25:46.809400
#now
print("The current date and time using today :n")
print(datetime.datetime.now(),end='n----------n') #2022-10-18 15:25:46.809399
#date
print("Setting date :n")
print(datetime.date(2019,11,7),end='n----------n') #2019-11-07
#time
print("Setting time :n")
print(datetime.time(6,30,23),end='n----------n') #06:30:23
#date.fromtimestamp
print("Converting seconds to date and time:n")
print(datetime.date.fromtimestamp(23456789),end='n----------n') #1970-09-29
#timedelta
b1=datetime.timedelta(days=30, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=4, weeks=8)
b2=datetime.timedelta(days=3, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=4, weeks=8)
b3=b2-b1
print(type(b3))
print("The resultant duration = ",b3,end='n----------n') #-27 days, 0:00:00
#attributes
a=datetime.datetime.now() #1
print(a)
print("The year is :",a.year) #2022
print("Hours :",a.hour) #15
python常用的时间time和datetime
最新推荐文章于 2024-10-08 20:27:53 发布