Python tutorial python date function instance

Source: Internet
Author: User
Tags date now
In python, the databases for date operations include datetime and time. no matter which language, date functions are certainly the most commonly used functions. in python, the databases for date operations include datetime and time.

In either language, date functions are the most commonly used functions. The following example code is directly used:

# 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 = '2017-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) # compare the number of days between two dates time_strA = '2017-07-29 09:05:00 'time _ strB = '2017-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 by {2} days '. format (time_strA, time_strB, str (sub_day.days) # Date n_days = 4now = datetime for the next n days. 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 '))

Running result:

>>>

2013-07-29 09:48:16

2013-07-29

2013-07-29 09:05:00

09:05:00 and 09:05:00 are 31 days different

The four days from today are:

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.