} } }

    python开辟_python日期操纵

    添加时间:2013-7-29 点击量:

    在python中对日期进行操纵的库有:



    1 import datetime
    
    2 import time


    对日期格局化信息,可以参考官方API:


    time.strftime


    datetime


    下面是我做的demo:



     1 datetime
    
    2
    3 import datetime
    4
    5 当前日期
    6 now = datetime.datetime.now()
    7 print(now.strftime(%Y-%m-%d %H:%M:%S))
    8 print(now.strftime(%Y-%m-%d))
    9
    10 string convert to datetime
    11 time_str = 2013-07-29 01:05:00
    12 str_convert_2_time = datetime.datetime.strptime(time_str, %Y-%m-%d %H:%M:%S
    13 print(str_convert_2_time)
    14
    15 斗劲两个日期相差几许天
    16 time_strA = 2013-07-29 01:05:00
    17 time_strB =2013-08-29 01:05:00
    18 day = datetime.datetime.strptime(time_strA, %Y-%m-%d %H:%M:%S
    19 day2 = datetime.datetime.strptime(time_strB, %Y-%m-%d %H:%M:%S
    20 sub_day = day2 - day
    21 print{0}和{1}相差{2}天.format(time_strA, time_strB, str(sub_day.days)))
    22
    23
    24 往后的n天的日期
    25 n_days = 4
    26 now = datetime.datetime.now()
    27 my_date = datetime.timedelta(days=n_days)
    28 n_day = now + my_date
    29 print从今天起的{0}天的日期是:.format(n_days))
    30 print(n_day.strftime(%Y-%m-%d %H:%M:%S))


    运行结果:



    Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:03:43) [MSC v.1600 32 bit (Intel)] on win32
    
    Type
    copyrightcredits or license() for more information.
    >>> ================================ RESTART ================================
    >>>
    2013-07-29 01:48:16
    2013-07-29
    2013-07-29 01:05:00
    2013-07-29 01:05:00和2013-08-29 01:05:00相差31天
    从今天起的4天的日期是:
    2013-08-02 01:48:16
    >>>


    原来,再大的房子,再大的床,没有相爱的人陪伴,都只是冰冷的物质。而如果身边有爱人陪伴,即使房子小,床小,也觉得无关紧要,因为这些物质上面有了爱的温度,成了家的元素。—— 何珞《婚房》#书摘#
    分享到: