Time and DateTime in Python (with code)

8dd0bf13dab16cbae3ba164df259189e.png

来源:DeepHub IMBA
本文约1300字,建议阅读6分钟
本文为每个场景提供带有代码和输出的说明性示例。

Python has two important modules when dealing with time-related operations: time and datetime. In this article, we introduce these two modules and provide illustrative examples with code and output for each scenario.

03813fb9b1c87aed1a0b7ed368b43757.jpeg

The time module is mainly used to handle time-related operations, such as obtaining the current time, calculating and formatting the time, etc. It provides several functions and constants, including:

  • time(): Returns the current timestamp (seconds since midnight, January 1, 1970).

  • ctime(): Convert a timestamp to a more readable string representation.

  • gmtime(): Convert a timestamp to a struct_time object of UTC time.

  • strftime(): Formats the time into the specified string format.

The datetime module is the main module for dealing with dates and times in Python, and it provides classes for representing and manipulating dates and times. mainly include:

  • datetime class: represents a specific date and time, including year, month, day, hour, minute, second and microsecond.

  • date class: represents the date, including year, month and day.

  • time class: represents time, including hours, minutes, seconds and microseconds.

  • timedelta class: represents a time interval, such as the difference between two dates.

  • datetime.now(): Returns the current date and time.

  • d atetime.strptime(): Parses a string into a datetime object.

Let's look at your example below.

time module

1. Measuring Execution Time‍

The time module is often used to measure the execution time of code segments. This is especially useful when optimizing code or comparing the performance of different algorithms.

 
  
import time


 start_time = time.time()


 # Code snippet to measure execution time


 end_time = time.time()
 execution_time = end_time - start_time


 print("Execution Time:", execution_time, "seconds")


 Execution Time: 2.3340916633605957 seconds

2. Suspension of execution

We may need to suspend program execution for a specific period of time. The time module provides the sleep() function for this purpose. Here's an example:

 
  
import time


 print("Hello")
 time.sleep(2)
 print("World!")

3. Get the current time

Get the current time in various formats. What the time() function does is: Returns the number of seconds since the Unix epoch (January 1, 1970).

import time


 current_time = time.time()
 print("Current Time (seconds since epoch):", current_time)

It can be seen that the time module is mainly used to represent timestamps (seconds since the Unix epoch) and some basic time-related operations, such as sleep and timing. It provides the function time() to get the current timestamp and other functions such as gmtime(), localtime() and strftime().

‍datetime 模块

1. Date and time

The datetime module provides classes such as datetime, date, and time to represent and manipulate dates and times. Here is an example of creating a datetime object:

 
  
from datetime import datetime


 current_datetime = datetime.now()
 print("Current DateTime:", current_datetime)

2. Date and time format

The strftime() method of datetime can format date and time as a string:

 
  
from datetime import datetime


 current_datetime = datetime.now()
 formatted_datetime = current_datetime.strftime("%Y-%m-%d %H:%M:%S")
 print("Formatted DateTime:", formatted_datetime)

3. Date and time operations

The datetime module provides methods to perform arithmetic operations on dates and times. Here is an example of calculating the difference between two datetime objects

 
  
from datetime import datetime, timedelta


 # Create two datetime objects
 start_datetime = datetime(2023, 5, 30, 10, 0, 0)
 end_datetime = datetime(2023, 5, 31, 15, 30, 0)


 # Calculate the difference between two datetime objects
 time_difference = end_datetime - start_datetime


 print("Time Difference:", time_difference)

4. Time zone conversion

Convert datetime objects between different timezones using the pytz library. Here's an example:

 
  
from datetime import datetime
 import pytz


 # Create a datetime object with a specific timezone
 dt = datetime(2023, 5, 31, 10, 0, 0, tzinfo=pytz.timezone('America/New_York'))


 # Convert the datetime object to a different timezone
 dt_utc = dt.astimezone(pytz.utc)


 print("Datetime in UTC:", dt_utc)

The datetime module provides more date and time operations. It contains the date, time, and datetime classes to create, represent, and manipulate date and time objects. These classes provide various methods for dealing with dates, times, datetime comparisons, operations, and formatting operations. For example, you can use datetime.now() to get the current date and time, use date.today() to get the current date, you can also add and subtract dates, calculate the difference between two dates, and so on. The datetime module also provides the timedelta class for representing time intervals. It can be used to add and subtract between dates and times, calculate time differences, and more.

Summarize

Both the time and datetime modules in Python provide basic functions for dealing with time-related operations. The time module is mainly used to process timestamps and some basic time operations, while the datetime module provides richer date and time processing functions, including the creation, comparison, operation and formatting of date and time objects.

When we want to deal with time, we can combine time and datetime modules according to different needs to effectively handle time-related tasks in Python programs, from simple time measurement to complex date and time operations. If you just need to represent and process time, use the time module. If you need to deal with dates and times, including date calculations, formatting, etc., you also need to use the datetime module.

By Ebo Jackson

Editor: Huang Jiyan

5283d5d665321d9f6aec8b579d041633.png

Guess you like

Origin blog.csdn.net/tMb8Z9Vdm66wH68VX1/article/details/131345796