1.获取当前时间并返回当前时间的日期和时间:fromdatetimeimportdatetimeprint(datetime.now())分别返回当前时刻的年月日:fromdatetimeimportdatetimeprint(datetime.now().year)print(datetime.now().month)print(datetime.now().day)返回当前时刻的周数:fromdatetimeimportdatetime#weekdayprint(datetime.now().weekday()+1)#某年的周数和日期print(datetime.now().isocalendar())2.指定日期和时间的格式fromdatetimeimportdatetime#使用date()函数结合日期和时间设置为只显示日期print(datetime.now().date())#使用时间()函数设置日期时间只显示日期print(datetime.now().time())#使用strftime()函数自定义日期时间print(datetime.now().strftime('%Y-%m-%d'))#使用strftime()函数自定义日期时间print(datetime.now().strftime("%Y-%m-%d%H:%M:%S"))3.字符串与时间格式转换将时间格式转换为字符串格式:fromdatetimeimportdatetime#新时间格式的时间,赋值给变量nownow=datetime.now()#使用str()函数将now转换为astringprint(type(str(now)))将字符串格式转换为时间格式:fromdateutil.parserimportparse#新建一个Timeinstringformatstr_time="2020-03-27"#使用解析函数parse()将str_time解析为时间print(type(parse(str_time)))4.时间索引importpandasaspdimportnumpyasnp#Createdatasetindex=pd.DatetimeIndex(['2018-01-01','2018-01-02','2018-01-03','2018-01-04','2018-01-05','2018-01-06','2018-01-07','2018-01-08','2018-01-09','2018-01-10'])data=pd.DataFrame(np.arange(1,11),columns=['num'],index=index)print(data)#获取2018年数据print(data["2018"])#获取2018年1月数据print(data["2018-01"])#getthedatafromJanuary1,2018toJanuary5,print(data["2018-01-01":"2018-01-05"])5.时间计算两个时间的区别:fromdatetimeimportdatetime#The两次时间差cha=datetime(2018,5,21,19,50)-datetime(2018,5,18,20,30)print(cha)#返回天数的时差print(cha.days)#return以秒为单位的时差print(cha.seconds)#转换以小时为单位的时差print(cha.seconds/3600)时间偏移(timedelta):fromdatetimeimporttimedeltafromdatetimeimportdatetimedate=datetime(2018,5,18,20,32)#往后推一天print(date+timedelta(days=1))#往后推60秒print(date+timedelta(seconds=60))#往前推onedayprint(date-t??imedelta(days=1))#向前推进60秒print(date-timedelta(seconds=60))时间偏移量(dateoffset):importpandasasppdfrompandas.tseries.offsetsimportDay,Hour,从datetime导入timedelta从datetime导入dateti分钟medate=datetime(2018,5,18,20,32)#倒推一天print(date+Day(1))#倒推1小时print(date+Hour(1))#倒推10分钟print(日期+分钟(10))文渊网,仅供学习,如有侵权,请联系删除。我的公众号【Python圈】汇集了优质的技术文章和经验总结。学习Python的路上肯定会遇到困难,不要慌张,我这里有一套学习资料,包括40+电子书,600+教学视频,涉及Python基础、爬虫、框架、数据分析、机学习等等,别怕学不会!
