SoFunction
Updated on 2025-04-14

Sharing of time and date processing techniques in Python

The most amazing thing about time is that it never waits for people! Just like you said you would get up after 5 minutes, but when you opened your eyes, it was already noon; or the boss asked you to count an Excel report, and you thought "it will be done in a while", but in the end, it was dark.

In the Python world, time is also very unique, with diverse formats, many time zones, and conversions can easily make people bald, but don’t worry, today we will talk about time and date processing in Python, so that you can change from a time novices to a time master!

1. Let’s start with a simple “time basic operation”

If you are a beginner in Python, you will definitely use itdatetimeModule. Let's start with the simplest creation and output time.

Get the current time

import datetime
now = ()
print(now)

This code is simple and clear.()The current date and time will be returned. For example:

2025-03-19 12:30:45.678901

Of course, you can also customize the format to output the time.

Format output

formatted_time = ("%Y-%m-%d %H:%M:%S")
print(formatted_time)

This code usesstrftimeMethod to format date and time. Common formatting codes include:

Format characters meaning
%Y Four Years (2025)
%m Month (01-12)
%d Date (01-31)
%H Hours (00-23)
%M Minutes (00-59)
%S Seconds (00-59)

The output result is similar:

2025-03-19 12:30:45

Is this a tidy look than the original time output?

2. Convert from a string to a date object

If you get a time string from a file or user input, how can you convert it into a date object in Python? Don't worry, this question is very simple.strptimeMethod to help.

time_str = "2025-03-19 12:30:45"
time_obj = (time_str, "%Y-%m-%d %H:%M:%S")
print(time_obj)

here,strptimeThe method will convert the time string into adatetimeObject. The conversion result will be a standard date and time object, which can continue to perform various operations.

3. Time addition and subtraction operation

Get the future or past time

Sometimes you may need to get a date for the first few days or the next few days. For example, suppose today is March 19, 2025, and you want to know the date after 7 days. passtimedelta, this can be done easily.

today = ()
delta = (days=7)
future_date = today + delta
print(future_date)

Output result:

2025-03-26 12:30:45.678901

Similarly, you can also do subtraction of dates to get a date in the past.

past_date = today - delta
print(past_date)

Output result:

2025-03-12 12:30:45.678901

4. Handle time zones and daylight saving time

As you may know, it is a bit troublesome to deal with time zones because there will be time difference between different time zones. Moreover, daylight saving time (DST) can cause you a headache. For example, the difference between Beijing time and New York time will vary with the daylight saving time. How to deal with these problems? The answer ispytzlibrary.

Install pytz library

pip install pytz

Set the time zone

import pytz
now = (("Asia/Shanghai"))
print(now)

ny_time = (("America/New_York"))
print(ny_time)

passpytz, you can set the time zone and handle the conversion of daylight saving time correctly. If you are working on applications involving global users, this library can really help you avoid a lot of trouble.

5. Processing date range

Sometimes we need to generate a date range, such as from January 1, 2025 to January 10, 2025. This can be useddate_rangeCome and do it easily.

import pandas as pd
date_range = pd.date_range(start="2025-01-01", end="2025-01-10")
print(date_range)

The output result is a date range:

DatetimeIndex(['2025-01-01', '2025-01-02', '2025-01-03', '2025-01-04',
               '2025-01-05', '2025-01-06', '2025-01-07', '2025-01-08',
               '2025-01-09', '2025-01-10'],
              dtype='datetime64[ns]', freq='D')

Very suitable for generating log timestamps, scheduling tasks, etc.

6. Uncommon but practical time operations

What day of the week

now = ()
weekday = ()  # Monday is 0, Sunday is 6print(f"Today is the week{weekday + 1}")

This code will return today's day of the week, and the output is similar to "Today is 3".

Get the number of days in the month

import calendar
year, month = 2025, 2
days_in_month = (year, month)[1]
print(f"{year}Year{month}There is a month {days_in_month} sky")

This code will return how many days there will be in a certain month of a certain year, such as: "28 days in February 2025"

Get the first and last days of a month

from datetime import date
first_day = date(year, month, 1)
last_day = date(year, month, days_in_month)
print(first_day, last_day)

Get the current timestamp

If you need a timestamp (seconds since January 1, 1970), you can usetimestamp()

timestamp = ().timestamp()
print(timestamp)

Convert to UTC time

If you need to convert local time to UTC time:

now_utc = ()
print(now_utc)

Determine whether a year is a leap year

def is_leap_year(year):
    return (year)

print(is_leap_year(2024))  # True (leap year)print(is_leap_year(2025))  # False (common year)

Calculate the working days between two dates

import numpy as np
start_date = (2025, 3, 1)
end_date = (2025, 3, 10)
workdays = np.busday_count(start_date.strftime('%Y-%m-%d'), end_date.strftime('%Y-%m-%d'))
print(f"Working days: {workdays}")

summary

Today, we have learned how to deal with time and dates in Python through some simple and practical code. Although time and date seem to be a very basic part, the details are really a big pit, especially time zones, daylight saving time and other issues. Therefore, mastering these basic techniques will not only make your code more accurate, but also avoid a lot of trouble caused by time errors.

The above is the detailed content shared by the time and date processing techniques in Python. For more information about Python time and date processing, please follow my other related articles!