Python date and time

Nov 23, 2016 am 10:39 AM
python

Python programs can handle dates and times in many ways. Converting date formats is a common routine chore. Python has a time and calendar module that can help.

What is Tick?

Time interval is a floating point decimal in seconds.

Each timestamp is expressed as how much time has passed since midnight (epoch) on January 1, 1970.

The popular time module that comes with Python has many functions to convert common date formats. For example, the function time.time() uses ticks to return the current operating system time recorded starting from 12:00am, January 1, 1970 (epoch), as shown in the following example:

#!/usr/bin /python

import time; # This is required to include time module.

The above example output result:

Number of ticks since 12:00am, January 1, 1970: 7186862.73399

Tick unit is most suitable for date calculations. But dates before 1970 cannot be expressed in this way. Dates that are too far away will not work, UNIX and Windows only support a date in 2038.

What is a time tuple?

Many Python functions use one element to assemble 9 groups of numbers. Processing time:

serial number

field

value

0 4-digit year 2008

1 month 1 to 12

2 days 1 to 31

3 hours 0 to 23

4 minutes

5 seconds 0 to 61 (60 or 61 is a leap second)

6 Day of the week 0 to 6 (0 is Monday)

7 one year Day 1 to 366 (Julian calendar)

8 Daylight Saving Time -1, 0, 1, -1 is the flag to determine whether it is daylight saving time

Above That is, the struct_time tuple. This structure has the following attributes:

serial number

attribute

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 determines whether it is daylight saving time

Get the current time

Convert from the time deletion method that returns a floating point number to a time tuple, as long as the floating point number is passed to a function such as localtime. S#!/USR/Bin/Python

import Time;

The output result of the above example:

Local current time : time.struct_time(tm_year=2013, tm_mon=7,

tm_mday=17, tm_hour=21, tm_min=26, tm_sec= 3, tm_wday =2, tm_yday=198, tm_isdst=0)

Get formatted time

You can choose various formats according to your needs, but the simplest function to get a readable time pattern is asctime( : ", localtime

The above example output result:

Local current time : Tue Jan 13 10:17:09 2009

Get a calendar for a certain month

Calendar The module has a wide range of methods for handling annual and monthly calendars, such as printing a monthly calendar for a certain month:

#!/usr/bin/python

import calendar

cal = calendar.month(2008, 1)

print "Here is the calendar:"

print cal;

The output result of the above example:

Here is the calendar:

January 2008

Mo Tu We Th Fr Sa Su

1 2 3 4 5 6

7 8 9 10 11 12 13

14 15 16 17 18 19 20

21 22 23 24 25 26 27

28 29 30 31

Time module

Time module contains the following built-in Functions, both for time processing and for converting time formats:

Serial number

Function and description

1 time.altzone
Returns the offset seconds of the daylight saving time area west of Greenwich. Negative values ​​are returned if the area is east of Greenwich (such as Western Europe, including the UK). Available only in regions where daylight saving time is enabled.

2 time.asctime([tupletime])
Accepts a time tuple and returns a readable form of "Tue Dec 11 18:07:14 2008" (Tuesday, December 11, 2008 18:07:14) A 24-character string.

3 time.clock( )
Returns the current CPU time in seconds calculated as a floating point number. It is used to measure the time consumption of different programs and is more useful than time.time().

4 elapsed floating point seconds) and returns a time tuple t in Greenwich astronomical time. Note: t.tm_isdst is always 0


6 time.localtime([secs])

Receives the time out (the number of floating point seconds elapsed after the 1970 epoch) and returns the time tuple t in local time (t.tm_isdst can be 0 or 1, depending on whether it is daylight saving time or not).


7 time.mktime(tupletime)

Accepts a time tuple and returns the time (the number of floating point seconds elapsed since epoch 1970).


8 time.sleep(secs)

Delay the running of the calling thread, secs refers to the number of seconds.


9 time.strftime(fmt[,tupletime])

Receives a time tuple and returns the local time represented as a readable string. The format is determined by fmt.


10 time.strptime(str,fmt='%a %b %d %H:%M:%S %Y')

Parse a time string into a time tuple according to the format of fmt.


11 time.time( )

Returns the timestamp of the current time (the number of floating point seconds elapsed since the 1970 epoch).


12 time.tzset()

Reinitialize time-related settings according to the environment variable TZ.


Time module contains the following 2 very important attributes:


serial number

attributes and descriptions

1 time.timezone

attribute time.timezone is the distance between the local time zone (without daylight saving time) and Greenwich Offset seconds (>0, Americas; <=0 most of Europe, Asia, Africa).

2 time.tzname

The attribute time.tzname contains a pair of strings that vary depending on the situation, which are the local time zone name with and without daylight saving time.


Calendar module

The functions of this module are all calendar-related, such as printing the character calendar of a certain month.

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

Serial number

Function and description

1 calendar.calendar(year,w=2,l=1,c=6)

Returns year in a multi-line string format Annual calendar, 3 months per row, interval distance is c. Daily width interval is w characters. The length of each line is 21* W+18+2* C. l is the number of lines per week.

2 calendar.firstweekday( )

Returns the setting of the current weekly starting day. By default, 0 is returned when the caendar module is first loaded, which is Monday.


3 calendar.isleap(year)

returns True if it is a leap year, otherwise it is false.


4 calendar.leapdays(y1,y2)

Returns the total number of leap years between Y1 and Y2.


5 calendar.month(year,month,w=2,l=1)

Returns a year and month calendar in multi-line string format, with two lines of title and one line for each week. Daily width interval is w characters. The length of each line is 7* w+6. l is the number of lines per week.


6 calendar.monthcalendar(year,month)

Returns a single-level nested list of integers. Each sublist holds an integer representing a week. Dates outside Year, month, and month are all set to 0; days within the range are represented by the day of the month, starting from 1.


7 calendar.monthrange(year,month)

Returns two integers. The first is the date code of the day of the week of the month, and the second is the day code of the month. Days range from 0 (Monday) to 6 (Sunday); months range from 1 to 12.


8 calendar.prcal(year,w=2,l=1,c=6)

is 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 day code of each week. 0 (Monday) to 6 (Sunday).

11 calendar.timegm(tupletime)
is the opposite of time.gmtime: it accepts a time tuple form and returns the time at that moment (the number of floating point seconds elapsed after the 1970 epoch).

12 calendar.weekday(year,month,day)
Returns the date code of the given date. 0 (Monday) to 6 (Sunday). Months range from 1 (January) to 12 (December).


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

Can vscode be used for mac Can vscode be used for mac Apr 15, 2025 pm 07:36 PM

VS Code is available on Mac. It has powerful extensions, Git integration, terminal and debugger, and also offers a wealth of setup options. However, for particularly large projects or highly professional development, VS Code may have performance or functional limitations.

Can vscode run ipynb Can vscode run ipynb Apr 15, 2025 pm 07:30 PM

The key to running Jupyter Notebook in VS Code is to ensure that the Python environment is properly configured, understand that the code execution order is consistent with the cell order, and be aware of large files or external libraries that may affect performance. The code completion and debugging functions provided by VS Code can greatly improve coding efficiency and reduce errors.

See all articles