python的date和datetime模块

#__Author: "Skiler Hao"
#date: 2017/2/15 11:06
"""
主要是测试和练习时间模块的使用

时间主要有字符串格式、时间戳 和 结构化时间元祖

一、date模块

字符串模式:Wed Feb 15 11:40:23 2017
时间戳格式:1463846400.0
结构化时间元祖:time.struct_time(tm_year=2017, tm_mon=2, tm_mday=15, tm_hour=11, tm_min=40, tm_sec=23, tm_wday=2, tm_yday=46, tm_isdst=0)

时间元祖是时间类型转化的关键
"""

import datetime
import time

#获取当前的时间,以三种格式展示出来

 

 

print(time.asctime()) #返回时间字符串Wed Feb 15 11:15:21 2017

print(time.localtime()) # 返回的是<class 'time.struct_time'>,例如time.struct_time(tm_year=2017, tm_mon=2, tm_mday=15, tm_hour=11, tm_min=21, tm_sec=2, tm_wday=2, tm_yday=46, tm_isdst=0)
print(type(time.time())) #返回的是float类型的当前时间戳

time.ctime()

#--------------时间类型转换
string_2_struct = time.strptime("2016/05/22","%Y/%m/%d") #将字符串转化成时间元祖
print(time.gmtime(time.time())) #将时间戳转换成时间元祖格式


struct_2_stamp = time.mktime(string_2_struct) #将时间元祖转化成时间戳
print(struct_2_stamp)


print(time.strftime("%Y-%m-%d %H:%M:%S",time.gmtime()) ) #将utc struct_time格式转成指定的字符串格式


#------------其他用途的时间函数
print(time.process_time()) #处理器计算时间
time.sleep(2) #睡眠指定的时间

 

二、datetime模块的使用和说明

datetime是基于time模块封装的,使用起来更加友好,但是执行效率略低。datetime里有四个重要的类:datetime、date、time、timedelta

1、datetime类:

  创建datetime对象:

    datetime.datetime (year, month, day[ , hour[ , minute[ , second[ , microsecond[ , tzinfo] )

    datetime.fromtimestamp(cls, timestamp, tz=None)

     datetime.utcfromtimestamp(cls, timestamp)

    datetime.now(cls, tz=None)

    datetime.utcnow(cls)

    datetime.combine(cls, datetime.date, datetime.time)

  datetime的实例方法:

    datetime.year、month、day、hour、minute、second、microsecond、tzinfo:
    datetime.date():获取date对象;
    datetime.time():获取time对象;
    datetime. replace ([ year[ , month[ , day[ , hour[ , minute[ , second[ , microsecond[ , tzinfo] ] ] ] ] ] ] ]):
    datetime. timetuple ()
    datetime. utctimetuple ()
    datetime. toordinal ()
    datetime. weekday ()
    datetime. isocalendar ()
    datetime. isoformat ([ sep] )
    datetime. ctime ():返回一个日期时间的C格式字符串,等效于time.ctime(time.mktime(dt.timetuple()));
    datetime. strftime (format)

2、timedelta类

 

 

 

#-------------------------计算相识时间-------------
def firstTimeToNow():
now = datetime.datetime.now()
first_time_tuple = datetime.datetime.strptime("2017/01/24","%Y/%m/%d")
return (now - first_time_tuple).days
print("相见相识,第"+str(firstTimeToNow())+"天")

 

posted @ 2017-02-20 11:03  skiler  阅读(14198)  评论(0编辑  收藏  举报