python 基础 7.1 datetime 获得时间

一 datatime 的使用
  object
        timedeta
        tzinfo
        time
        data
               datatime
     
      time: 在python文档里,time是归类在generk  operating  system services 中,换句话说,它提供的功能是更加接近于操作系统层面。
 
      python 开发过程中,我们经常用到获取当前时间,根据当前时间生成一个和当天时间相关的文件,这样我们在后期查找文件的时候就方便了很多,那python 又如何来获取当前时间的呢?
          from dateime import datetime
           now_time = datetime.now()
           a = now_time.strftime('%Y-%m-%d')
           print(now_time)
           print a
           print(type(now_time))
 
   strftime 时间参数有很多,介绍一些常用的时间参数:
   格式参数:
      %Y   带世纪部分的十进制年份
      %m  十进制表示的月份
       %d   十进制表示的每月的第几天
        %H   24小时制的小时
       %M     十时制表示的分钟数
         %s     十进制的秒数
         %c      标准时间
 
示例1:
#/usr/bin/python
#coding=utf-8
#@Time   :2017/11/8 14:10
#@Auther :liuzhenchuan
#@File   :datatime.py
 
#time模块基本不用于取时间,取时间用datatime 模块
# time独有用法,alt + enter
import time
 
for i in xrange(1,10):
    print i
    time.sleep(0.3)
 
#datatime  获取当前时间
from datetime import datetime
now_time = datetime.now()
print now_time
 
#strftime 显示时间的格式
new1_time = now_time.strftime('%Y-%m-%d')
print new1_time
new2_time = now_time.strftime('%Y-%m-%d %H:%M:%S')
print new2_time
 
#打印标准时间
new3_time = now_time.strftime('%c')
print new3_time
 
>>>
1
2
3
4
5
6
7
8
9
2017-11-08 21:27:11.254000
2017-11-08
2017-11-08 21:27:11
11/08/17 21:27:11
 
 
 
示例2:
import datetime,timedelta
#timedelta 获取昨天的时间
now1_time = datetime.now()
yesterday = now1_time + timedelta(days=-1)
print yesterday
 
>>>
2017-11-07 22:01:51.766000
 
 
 
#打印明天的时间
tomorrow = now1_time + timedelta(days= +1)
tomorrow1 = tomorrow.strftime('%Y-%m-%d')
tomorrow1 = tomorrow.strftime('%c')
print tomorrow1
 
>>>  2017-11-09
            11/09/17 22:09:06
 
 
  
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
posted @ 2017-11-09 10:24  刘振川的博客  阅读(538)  评论(0编辑  收藏  举报