Python Date and time

Source: Internet
Author: User
Tags month name string format

PythonDate and Time reprint: http://www.runoob.com/python/python-date-time.html

The Python program can handle dates and times in many ways, and converting date formats is a common feature.

Python provides a time and calendar module that can be used to format dates and times.

The time interval is a floating-point decimal in seconds.

Each timestamp is represented by how long it has been since midnight on January 1, 1970 (the calendar).

There are many functions under the time module of Python to convert common date formats. such as the function Time.time () is used to get the current timestamp, as in the following instance:

#!/usr/bin/python#-*-coding:utf-8-*-import time;  # introduce time module ticks = time.time () print "Current timestamp is:", ticks

The result of the above example output:

The current timestamp is: 1459994552.51

Timestamp units are best suited for date operations. But the dates before 1970 cannot be expressed in this way. Too far away from the date, UNIX and Windows only support to 2038 years.

What is a time tuple?

Many Python functions use a single element to assemble 9 sets of digital processing time:

Serial Number Field value
0 4-digit years 2008
1 Month 1 to 12
2 Day 1 to 31
3 Hours 0 to 23
4 Minutes 0 to 59
5 Seconds 0 to 61 (60 or 61 is a leap second)
6 The first day of the week 0 to 6 (0 is Monday)
7 The first day of the year 1 to 366 (Julian calendar)
8 Daylight saving time -1, 0, 1,-1 is the flag that decides whether to be daylight saving time

The above is also the struct_time tuple. This structure has the following properties:

Serial Number Properties value
0 Tm_year 2008
1 Tm_mon 1 to 12
2 Tm_mday 1 to 31
3 Tm_hour 0 to 23
4 Tm_min 0 to 59
5 Tm_sec 0 to 61 (60 or 61 is a leap second)
6 Tm_wday 0 to 6 (0 is Monday)
7 Tm_yday 1 to 366 (Julian calendar)
8 Tm_isdst -1, 0, 1,-1 is the flag that decides whether to be daylight saving time

Get current time

Converts from the time of the return floating-point number to the time tuple, as long as the floating-point number is passed to a function such as localtime.

#!/usr/bin/python#-*-coding:utf-8-*-import timelocaltime = Time.localtime (Time.time ()) print "local time:", localtime

The result of the above example output:

local time: Time.struct_time (tm_year=2016, tm_mon=4, tm_mday=7, tm_hour=10, tm_min=3, tm_sec=27, tm_wday=3, tm_yday=98, tm_ isdst=0)

Get the formatted time

You can choose a variety of formats according to your needs, but the simplest function to get a readable time pattern is asctime ():

#!/usr/bin/python#-*-coding:utf-8-*-import timelocaltime = Time.asctime (Time.localtime (Time.time ())) print "local time:" , localtime

The result of the above example output:

local time: Thu APR  7 10:05:21 2016
Formatted date

We can use the Strftime method of the time module to format the date:

Time.strftime (format[, T])
#!/usr/bin/python#-*-coding:utf-8-*-import time# formatted as 2016-03-20 11:45:39 form print time.strftime ("%y-%m-%d%h:%m:%s", Time.localtime ()) # formatted into Sat Mar 28 22:24:24 2016 form print time.strftime ("%a%b%d%h:%m:%s%Y", Time.localtime ())   # will format word string conversion to timestamp a = "Sat Mar 22:24:24" Print Time.mktime (Time.strptime (A, "%a%b%d%h:%m:%s%Y"))

The result of the above example output:

2016-04-07 10:25:09thu Apr 07 10:25:09 20161459175064.0

Python format symbols in time Date:

    • %y Two-digit year representation (00-99)
    • %Y Four-digit year representation (000-9999)
    • %m Month (01-12)
    • One day in%d months (0-31)
    • %H 24-hour hours (0-23)
    • %I 12-hour hours (01-12)
    • %M minutes (00=59)
    • %s seconds (00-59)
    • %a Local Simplified Week name
    • %A Local Full week name
    • %b a locally simplified month name
    • %B Local Full month name
    • %c Local corresponding date representation and time representation
    • %j Day of the Year (001-366)
    • %p the equivalent of a local a.m. or p.m.
    • %u weeks of the year (00-53) Sunday is the beginning of the week
    • %w Week (0-6), Sunday for the beginning of the week
    • %W Week of the Year (00-53) Monday is the beginning of the week
    • %x Local corresponding date representation
    • %x Local corresponding time representation
    • %Z the name of the current time zone
    • Percent% of the number itself
Get a calendar for a month

The Calendar module has a wide range of methods for working with calendar and monthly calendars, such as printing a month's monthly calendar:

#!/usr/bin/python#-*-coding:utf-8-*-import calendarcal = calendar.month (1) print "The following output January 2016 calendar:" Print cal;

The result of the above example output:

The following output January 2016 calendar:    January 2016Mo Tu We Th Fr Sa Su             1  2  3 4  5  6  7  8  9 1011 12 13 14 15 1 6 1718 19 20 21 22 23 2425 26 27 28 29 30 31

Time Module

The time module contains the following built-in functions, both temporal and conversion time formats:

Serial Number Functions and descriptions
1 Time.altzone
Returns the number of seconds to offset the daylight saving time region in West Greenwich. If the region returns negative values in eastern Greenwich (such as Western Europe, including the UK). Available for daylight saving time enabled regions.
2 Time.asctime ([Tupletime])
Accepts a time tuple and returns a read-only string of 24 characters in the form "Tue Dec 11 18:07:14 2008" (December 11, 2008 Tuesday 18:07 14 seconds).
3 Time.clock ()
The number of seconds used to calculate the floating-point count returns the current CPU time. It is more useful than time.time () to measure the time spent on different programs.
4 Time.ctime ([secs])
function equivalent to Asctime (localtime (secs)), parameter is not given equal to Asctime ()
5 Time.gmtime ([secs])
Receives the time suffix (the number of floating-point seconds elapsed after the 1970 era) and returns the time-tuple T in Greenwich Astronomical time. Note: T.TM_ISDST is always 0
6 Time.localtime ([secs])
The Receive time suffix (the number of floating-point seconds after the 1970 era) and the time-of-day tuple T (t.tm_isdst 0 or 1, depending on whether the local time is daylight saving).
7 Time.mktime (Tupletime)
Accepts the time tuple and returns the time suffix (the number of floating-point seconds elapsed after the 1970 era).
8 Time.sleep (secs)
Postpone the call thread's run, secs refers to the number of seconds.
9 Time.strftime (Fmt[,tupletime])
Receives a time tuple and returns the local time as a readable string, formatted as determined by the FMT.
10 Time.strptime (str,fmt= '%a%b%d%h:%m:%s%Y ')
Resolves a time string to a time tuple according to the format of the FMT.
11 Time.time ()
Returns the timestamp of the current time (the number of floating-point seconds elapsed after the 1970 era).
12 Time.tzset ()
Re-initializes time-related settings according to the environment variable TZ.

The time module contains the following 2 very important properties:

Serial Number Properties and Descriptions
1 Time.timezone
The attribute Time.timezone is the number of seconds (>0, Americas; <=0 most of Europe, Asia, and Africa) from Greenwich in the local time zone (daylight saving is not started).
2 Time.tzname
The Time.tzname property contains a pair of different strings depending on the situation, which is the local time zone name with daylight savings, and No.

Calendar Module

The functions of this module are calendar-related, such as printing a month's character calendar.

Monday is the default first day of the week, and Sunday is the default last day. You need to call the Calendar.setfirstweekday () function to change the settings. The module contains the following built-in functions:

Serial Number Functions and descriptions
1 Calendar.calendar (year,w=2,l=1,c=6)
Returns the year calendar of a multi-line string format with a 3-month line with a distance of C. The daily width interval is w characters. The length of each line is 21* w+18+2* C. L is the number of rows per week.
2 Calendar.firstweekday ()
Returns the settings for the current weekly start date. By default, 0 is returned when the Caendar module is first loaded, which is Monday.
3 Calendar.isleap (year)
is a leap year that returns true, otherwise false.
4 Calendar.leapdays (Y1,y2)
Returns the total number of leap years between y1,y2 two.
5 Calendar.month (year,month,w=2,l=1)
Returns a multi-line string format for year month calendar, two row headings, and one week row. The daily width interval is w characters. The length of each line is 7* w+6. L is the number of rows per week.
6 Calendar.monthcalendar (Year,month)
Returns a single-level nested list of integers. Each sub-list is loaded with integers representing one weeks. The date of year month is set to 0, and the day of the month is indicated by the day of the week, starting from 1.
7 Calendar.monthrange (Year,month)
Returns a two integer. The first is the day of the week of the month, and the second is the date code for that month. Day from 0 (Monday) to 6 (Sunday); The month is from 1 to 12.
8 Calendar.prcal (year,w=2,l=1,c=6)
Equivalent to print Calendar.calendar (year,w,l,c).
9 Calendar.prmonth (year,month,w=2,l=1)
Equivalent to print Calendar.calendar (year,w,l,c).
10 Calendar.setfirstweekday (Weekday)
Set the starting date code for the week. 0 (Monday) to 6 (Sunday).
11 CALENDAR.TIMEGM (Tupletime)
In contrast to Time.gmtime: accepts a time tuple form, returning the time suffix (the number of floating-point seconds elapsed after the 1970 era).
12 Calendar.weekday (Year,month,day)
Returns the date code for the given date. 0 (Monday) to 6 (Sunday). The month is 1 (January) to 12 (December).

Other related modules and functions

In Python, other modules that handle the date and time are:

      • DateTime module
      • Pytz Module
      • Dateutil Module

Python Date and time

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.