Time and datatime)

Source: Internet
Author: User
Tags timedelta
The time and date functions in python are described in time and datatime. For more information, see 1. obtain the current time in two ways:

The code is as follows:


Import datetime, time
Now = time. strftime ("% Y-% m-% d % H: % M: % S ")
Print now
Now = datetime. datetime. now ()
Print now

2. get the date of the last day of the last month (the first day of the month minus one day)

The code is as follows:


Last = datetime. date (datetime. date. today (). year, datetime. date. today (). month, 1)-datetime. timedelta (1)
Print last

3. get the time difference (unit: seconds, usually used for calculating the time when the program runs)

The code is as follows:


Starttime = datetime. datetime. now ()
# Long running
Endtime = datetime. datetime. now ()
Print (endtime-starttime). seconds

4. calculate the last 10 hours of the current time.

The code is as follows:


D1 = datetime. datetime. now ()
D3 = d1 + datetime. timedelta (hours = 10)
D3.ctime ()

Common classes include datetime and timedelta. They can be added or subtracted from each other. Each class has some methods and attributes to view specific values, such as datetime: day, hour, and weekday; timedelta can be viewed as days and seconds.

5. time and date formatting symbols in python:

% Y two-digit year (00-99)
% Y indicates the four-digit year (000-9999)
% M month (01-12)
One day in % d Month (0-31)
% H Hour in 24-hour format (0-23)
% I 12-hour (01-12)
% M minutes (00 = 59)
% S seconds (00-59)

% A local simplified week name
% A Local full week name
% B local simplified month name
% B local full month name
% C local date and time
% J one day in the year (001-366)
% P local equivalent of A. M. or P. M.
% U number of weeks in a year (00-53) Sunday is the start of the week
% W week (0-6), Sunday is the beginning of the week
% W number of weeks in a year (00-53) Monday is the start of the week
% X local date representation
% X local time representation
% Z current time zone name
% Itself

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.