Python Tutorial Python Date function instance

Source: Internet
Author: User
The libraries that manipulate dates in Python are: datetime, TIME

In any language, the date function is definitely the most commonly used function. Directly below the instance code

#datetimeimport datetime# Current Date now = Datetime.datetime.now () print (Now.strftime ('%y-%m-%d%h:%m:%s ')) print ( Now.strftime ('%y-%m-%d ')) #string convert to Datetimetime_str = ' 2013-07-29 09:05:00 ' str_convert_2_time = Datetime.datetime.strptime (Time_str, '%y-%m-%d%h:%m:%s ') print (str_convert_2_time) #比较两个日期相差多少天time_strA = ' 2013-07-29 09:05:00 ' time_strb = ' 2013-08-29 09:05:00 ' day = Datetime.datetime.strptime (Time_stra, '%y-%m-%d%h:%m:%s ') Day2 = Datetime.datetime.strptime (TIME_STRB, '%y-%m-%d%h:%m:%s ') Sub_day = Day2-dayprint (' {0} and {1} differ {2} days '. Format (time _stra, TIME_STRB, str (sub_day.days))) #今后的n天的日期n_days = 4now = Datetime.datetime.now () my_date = Datetime.timedelta (days =n_days) N_day = now + my_dateprint (' the date of {0} days from today is: '. Format (n_days)) print (N_day.strftime ('%y-%m-%d%h:%m:%s ')

Operation Result:

>>>

2013-07-29 09:48:16

2013-07-29

2013-07-29 09:05:00

2013-07-29 09:05:00 and 2013-08-29 09:05:00 difference 31 days

The 4-day date from today is:

2013-08-02 09:48:16

>>>

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.