Table of Contents
Module for processing date and time in Python
time module
Find dates and times using the time module
datetime module
使用 datetime 查找日期和时间
Home Backend Development Python Tutorial Super summary of Python date and time usage

Super summary of Python date and time usage

Apr 13, 2023 am 10:58 AM
python date usage

Time is undoubtedly one of the most critical factors in all aspects of life, therefore, recording and tracking time becomes very important. In Python, you can track dates and times through its built-in libraries. Today we will introduce about date and time in Python, and learn how to use the time and datetime modules to find and modify dates and times.

Module for processing date and time in Python

Python provides time and datetime modules, which can help us easily obtain and modify date and time. Let us take a look at them one by one.

time module

This module includes all the time related functions required to perform various operations using time, it also allows us to access the clock types required for multiple purposes.

Built-in functions:

Please take a look at the following table, which describes some important built-in functions of the time module.

##time.struct_time ClassThe function either takes this class as a parameter or returns it as outputlocaltime()Takes the number of seconds elapsed since the epoch as a parameter and returns the date and time in the form of time. struct_time format##gmtime()
##function

Description

time()

Returns the number of seconds elapsed since the epoch

ctime()

takes the elapsed seconds as parameter and returns the current date and time

sleep ()

Stops the execution of a thread for the given duration

Similar to localtime(), returns the time. The reciprocal of struct_time

mktime()

ocaltime() in UTC format. Gets a tuple containing 9 parameters and returns the number of seconds elapsed since epoch pas output

asctime()

Get a tuple containing 9 parameters and return a string representing the same parameters

strftime()

Get a tuple containing 9 parameters and return a string representing the same parameters according to the format code used

strptime()

Analyze the string and return it in time. struct_time format

Code Formatting:

Before explaining each function with examples, let’s look at all the legal ways to format code:

Code

Description

Example

%a

##Weekday (short version)

Mon

%A

Weekday (full version)

Monday

%b

Month (short version)

Aug

%B

Month (full version)

August

%c

Local date and time version

Tue Aug 23 1:31:40 2019

%d

Depicts the day of the month (01-31)

07

%f

Microseconds

000000-999999

%H

Hour (00-23)

15

%I

Hour (00-11)

3

%j

Day of the year

235

%m

Month Number (01-12)

07

%M

Minutes (00-59)

44

%p

AM / PM

AM

%S

Seconds (00-59)

23

%U

Week number of the year starting from Sunday (00-53)

12

%w

Weekday number of the week

Monday (1)

%W

Week number of the year starting from Monday (00-53)

34

%x

Local date

06/07/22

%X

Local time

12:30:45

%y

Year (short version)

22

%Y

Year (full version)

2022

%z

UTC offset

0100

%Z

Timezone

CST

%%

% Character

%

The

struct_time class has the following attributes:

##0000, .., 2019, …, 9999tm_mon1-12tm_mday1-31tm_hour0-23tm_min0-59##tm_sec##tm_wday
##Attribute

Value

tm_year

0-61

0-6 (Monday is 0)

##tm_yday

1-366

tm_isdst

0, 1, -1    (daylight savings time, -1 when unknown)

Now let’s look at a few examples of the time module.

Find dates and times using the time module

Getting dates and times in Python is easy using the built-in functions and formatting code described in the table above.

import time
#time
a=time.time() #total seconds since epoch
print("Seconds since epoch :",a,end='n----------n')
#ctime
print("Current date and time:")
print(time.ctime(a),end='n----------n') 
#sleep
time.sleep(1) #execution will be delayed by one second
#localtime
print("Local time :")
print(time.localtime(a),end='n----------n')
#gmtime
print("Local time in UTC format :")
print(time.gmtime(a),end='n-----------n')
#mktime
b=(2019,8,6,10,40,34,1,218,0)
print("Current Time in seconds :")
print( time.mktime(b),end='n----------n')
#asctime
print("Current Time in local format :")
print( time.asctime(b),end='n----------n')
#strftime
c = time.localtime() # get struct_time
d = time.strftime("%m/%d/%Y, %H:%M:%S", c)
print("String representing date and time:")
print(d,end='n----------n')
#strptime
print("time.strptime parses string and returns it in struct_time format :n")
e = "06 AUGUST, 2019"
f = time.strptime(e, "%d %B, %Y")
print(f)

Output:

Seconds since epoch : 1565070251.7134922
———-
Current date and time:
Tue Aug 6 11:14:11 2019
———-
Local time :
time.struct_time(tm_year=2019, tm_mon=8, tm_mday=6, tm_hour=11, tm_min=14, tm_sec=11, tm_wday=1, tm_yday=218, tm_isdst=0)
———-
Local time in UTC format :
time.struct_time(tm_year=2019, tm_mon=8, tm_mday=6, tm_hour=5, tm_min=44, tm_sec=11, tm_wday=1, tm_yday=218, tm_isdst=0)
———–
Current Time in seconds :
1565068234.0
———-
Current Time in local format :
Tue Aug 6 10:40:34 2019
———-
String representing date and time:
08/06/2019, 11:14:12
———-
time.strptime parses string and returns it in struct_time format :

time.struct_time(tm_year=2019, tm_mon=8, tm_mday=6, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=218, tm_isdst=-1)

datetime module

Similar to the time module, the datetime module contains all the methods necessary to handle dates and times.

Built-in functions:

The following table introduces some important functions in this module:

##datetime()Constructor of datetime##datetime.today()datetime.now()date()time()##date.fromtimestamp()
##function

Description

Returns the current local date and time

Returns the current local date and time

Take the year, month, and day as parameters to create the corresponding date

Takes hours, minutes, seconds, microseconds and tzinfo as parameters and creates the corresponding date

Convert seconds to return the corresponding date and time

timedelta()

它是不同日期或时间之间的差异(持续时间)

使用 datetime 查找日期和时间

现在,让我们尝试实现这些函数,以使用datetime模块在 Python 中查找日期和时间。

import datetime
#datetime constructor
print("Datetime constructor:n")
print(datetime.datetime(2019,5,3,8,45,30,234),end='n----------n')
 
#today
print("The current date and time using today :n")
print(datetime.datetime.today(),end='n----------n')
 
#now
print("The current date and time using today :n")
print(datetime.datetime.now(),end='n----------n')
 
#date
print("Setting date :n")
print(datetime.date(2019,11,7),end='n----------n')

#time
print("Setting time :n")
print(datetime.time(6,30,23),end='n----------n')
 
#date.fromtimestamp
print("Converting seconds to date and time:n")
print(datetime.date.fromtimestamp(23456789),end='n----------n')
 
#timedelta
b1=datetime.timedelta(days=30, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=4, weeks=8)
b2=datetime.timedelta(days=3, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=4, weeks=8)
b3=b2-b1
print(type(b3))
print("The resultant duration = ",b3,end='n----------n')
 
#attributes
a=datetime.datetime.now() #1
print(a)
print("The year is :",a.year)
 
print("Hours :",a.hour)

Output:

Datetime constructor:

2019-05-03 08:45:30.000234
———-
The current date and time using today :

2019-08-06 13:09:56.651691
———-
The current date and time using today :

2019-08-06 13:09:56.651691
———-
Setting date :

2019-11-07
———-
Setting time :

06:30:23
———-
Converting seconds to date and time:
1970-09-29
———-
<class ‘datetime.timedelta’>
The resultant duration = -27 days, 0:00:00
———-
2019-08-06 13:09:56.653694
The year is : 2019
Hours : 13

The above is the detailed content of Super summary of Python date and time usage. For more information, please follow other related articles on the PHP Chinese website!

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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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)

Hot Topics

PHP Tutorial
1512
276
What are common strategies for debugging a memory leak in Python? What are common strategies for debugging a memory leak in Python? Aug 06, 2025 pm 01:43 PM

Usetracemalloctotrackmemoryallocationsandidentifyhigh-memorylines;2.Monitorobjectcountswithgcandobjgraphtodetectgrowingobjecttypes;3.Inspectreferencecyclesandlong-livedreferencesusingobjgraph.show_backrefsandcheckforuncollectedcycles;4.Usememory_prof

What is sentiment analysis in cryptocurrency trading? What is sentiment analysis in cryptocurrency trading? Aug 14, 2025 am 11:15 AM

Table of Contents What is sentiment analysis in cryptocurrency trading? Why sentiment analysis is important in cryptocurrency investment Key sources of emotion data a. Social media platform b. News media c. Tools for sentiment analysis and technology Commonly used tools in sentiment analysis: Techniques adopted: Integrate sentiment analysis into trading strategies How traders use it: Strategy example: Assuming BTC trading scenario scenario setting: Emotional signal: Trader interpretation: Decision: Results: Limitations and risks of sentiment analysis Using emotions for smarter cryptocurrency trading Understanding market sentiment is becoming increasingly important in cryptocurrency trading. A recent 2025 study by Hamid

How to automate data entry from Excel to a web form with Python? How to automate data entry from Excel to a web form with Python? Aug 12, 2025 am 02:39 AM

The method of filling Excel data into web forms using Python is: first use pandas to read Excel data, and then use Selenium to control the browser to automatically fill and submit the form; the specific steps include installing pandas, openpyxl and Selenium libraries, downloading the corresponding browser driver, using pandas to read Name, Email, Phone and other fields in the data.xlsx file, launching the browser through Selenium to open the target web page, locate the form elements and fill in the data line by line, using WebDriverWait to process dynamic loading content, add exception processing and delay to ensure stability, and finally submit the form and process all data lines in a loop.

How to implement a custom iterator within a Python class? How to implement a custom iterator within a Python class? Aug 06, 2025 pm 01:17 PM

Define__iter__()toreturntheiteratorobject,typicallyselforaseparateiteratorinstance.2.Define__next__()toreturnthenextvalueandraiseStopIterationwhenexhausted.Tocreateareusablecustomiterator,managestatewithin__iter__()oruseaseparateiteratorclass,ensurin

How to use enumerate to loop with an index in Python How to use enumerate to loop with an index in Python Aug 11, 2025 pm 01:14 PM

When you need to traverse the sequence and access the index, you should use the enumerate() function. 1. enumerate() automatically provides the index and value, which is more concise than range(len(sequence)); 2. You can specify the starting index through the start parameter, such as start=1 to achieve 1-based count; 3. You can use it in combination with conditional logic, such as skipping the first item, limiting the number of loops or formatting the output; 4. Applicable to any iterable objects such as lists, strings, and tuples, and support element unpacking; 5. Improve code readability, avoid manually managing counters, and reduce errors.

How to handle large datasets in Python that don't fit into memory? How to handle large datasets in Python that don't fit into memory? Aug 14, 2025 pm 01:00 PM

When processing large data sets that exceed memory in Python, they cannot be loaded into RAM at one time. Instead, strategies such as chunking processing, disk storage or streaming should be adopted; CSV files can be read in chunks through Pandas' chunksize parameters and processed block by block. Dask can be used to realize parallelization and task scheduling similar to Pandas syntax to support large memory data operations. Write generator functions to read text files line by line to reduce memory usage. Use Parquet columnar storage format combined with PyArrow to efficiently read specific columns or row groups. Use NumPy's memmap to memory map large numerical arrays to access data fragments on demand, or store data in lightweight data such as SQLite or DuckDB.

How to copy files and directories from one location to another in Python How to copy files and directories from one location to another in Python Aug 11, 2025 pm 06:11 PM

To copy files and directories, Python's shutil module provides an efficient and secure approach. 1. Use shutil.copy() or shutil.copy2() to copy a single file, which retains metadata; 2. Use shutil.copytree() to recursively copy the entire directory. The target directory cannot exist in advance, but the target can be allowed to exist through dirs_exist_ok=True (Python3.8); 3. You can filter specific files in combination with ignore parameters and shutil.ignore_patterns() or custom functions; 4. Copying directory only requires os.walk() and os.makedirs()

How to get the first and last day of the year in SQL? How to get the first and last day of the year in SQL? Aug 11, 2025 pm 05:42 PM

ThefirstdayoftheyearisobtainedbyconstructingortruncatingtoJanuary1stofthegivenyear,andthelastdayisDecember31stofthesameyear,withmethodsvaryingbydatabasesystem;2.Fordynamiccurrentyeardates,MySQLusesDATE_FORMATorMAKEDATE,PostgreSQLusesDATE_TRUNCorDATE_

See all articles