SoFunction
Updated on 2025-03-03

Detailed explanation of how to correctly use timestamps, dates, time zones in Python

Time concept

UTC and time zone

UTC is the abbreviation of Coordinated Universal Time and is the global standard of time. UTC time is not affected by time zones and daylight saving time, and is the standard of time. Times around the world are adjusted based on UTC time as a reference.

The time zone is Time Zone, which is a region on the earth divided by longitude. Each region has its own standard time. The gap between time zone and UTC time is usually in hours (but some time zones are offset by 30 minutes). The entire earth is divided into 24 main time zones, each covering approximately 15 degrees of longitude (360 degrees/24 hours)

Beijing time is East Eighth District, which is 8 hours off from UTC time, which is UTC+8. In the world, there are also Australia's regions in East Eighth District.

New York time is the West Five District, which is UTC-5, so the standard time difference from the East Eight District in Beijing time is 13 hours. But it should be noted that when the New York area starts daylight saving time, it will become UTC-4, which is a common 12-hour time difference.

Tokyo time is East Nine District, which is UTC+9. Therefore, the difference between East Eight District in Beijing time is 1 hour, and 1 hour early.

Daylight saving time

Daylight saving time is a system of artificial clock adjustments. It usually adjusts the clock forward for an hour in spring. Its purpose is to extend the sunshine time in the evening, aiming to make more efficient use of daylight resources and reduce energy consumption.

Among them, high-latitude countries in the northern hemisphere usually use daylight saving time because of their high latitude and great changes in sunshine. In contrast, sunshine changes in areas close to the equator, so daylight saving time is usually not used. For example, most Asian countries, such as China, Japan, and South Korea, do not use daylight saving time.

People who have not used the Summer Time area usually don’t know much about the role of Summer Time. Specifically: During Summer Time, the clock is turned up for an hour. This means that people actually wake up one hour earlier than usual according to the new schedule, but because it is early in summer, it has little impact on life. When you get off work in the afternoon, the sky is still bright at the new time and people can enjoy more sunshine after get off work.

Timestamp

Timestamp is a digital format that represents a specific time point. It is represented by the number of seconds or milliseconds elapsed since 00:00:00 on January 1, 1970. The time stamp can accurately identify a specific time point, which is not affected by the time zone.

Time stamps play a big role in programming, such as recording a system event, the time of user registration, or calculating the time interval by calculating the difference in timestamps.

time

General formatting

time mainly deals with time acquisition and simple formatting. If more complex date and time operations are required, you should try using datetime.

Commonly used formatting strings are shown below, and the same is true in datetime

  • %Y: Four-digit year
  • %m: Two months (01-12)
  • %d: two digit date (01-31)
  • %H: Two digits of hours (00-23)
  • %M: Two digit minutes (00-59)
  • %S: Two digits of seconds (00-59)

Timestamp

Get the current timestamp

import time
 
timestamp = ()
print("Current timestamp:", timestamp)

Time stamps can be used to record time intervals, but if you want to make more accurate timing, you can use it.

import time
 
start = time.perf_counter()
(2)
end = time.perf_counter()
print(f"Time-consuming operation: {end - start} Second")

Time stamp to time object

Convert timestamp to struct_time local time

timestamp = ()
local_time = (timestamp)
print("Local time:", local_time)

Convert timestamp to utc time

timestamp = ()
utc_time = (timestamp)
print("UTC Time:", utc_time)

Time object to time stamp

import time
 
struct = ("2024-11-02 22:00:00", "%Y-%m-%d %H:%M:%S")
timestamp = (struct)
print("Timestamp:", timestamp)  # Timestamp: 1730556000.0

Time formatting

Quickly convert a timestamp to readable time

timestamp = ()
readable_time = (timestamp)
print(readable_time)  # Format such as Sat Nov 2 10:32:27 2024

Create a time object based on a time string

time_str = "2024-11-02 22:00:00"
parsed_time = (time_str, "%Y-%m-%d %H:%M:%S")
 
print(parsed_time)

Convert to string according to time object

time_str = "2024-11-02 22:00:00"
parsed_time = (time_str, "%Y-%m-%d %H:%M:%S")
 
formatted_time = ("%Y year %m month %d day %H point %M point", parsed_time)
print("Format time:", formatted_time)  # Format time: 22:00 on November 2, 2024

Time pause

Time will not be paused, but in fact this function is paused by the program.

import time
 
print("Before pause")
(3)  # Pause for 3 secondsprint("After pause")

datetime

date date

Get the current date

today = ()
print("Today's date:", today)  # Format as 2024-11-02

datetime datetime

Get the current time

now_time = ().time()
print("Current time:", now_time)  # Format as 10:46:50.506231

Get the current date and time

now = ()
print("Current date and time:", now)  # Format as 2024-11-02 10:47:44.299445

Get UTC time

utc_now = ()
print("UTC Time:", utc_now)

Create a datetime object

Create a date object

specific_date = (2024, 11, 2)
print("Specific date:", specific_date)

Create a time object

specific_time = (22, 0, 0)
print("Specific time:", specific_time)

Create a datetime object

specific_datetime = (2024, 11, 2, 22, 0, 0)
print("Specific date and time:", specific_datetime)

Time string formatting and parsing

Time string formatting

now = ()
formatted = ("%Y-%m-%d %H:%M:%S")
print("Format date time:", formatted)

Time string parsing

time_str = "2024-11-2 22:00:00"
parsed_datetime = (time_str, "%Y-%m-%d %H:%M:%S")
print("Resolved Date and Time Object:", parsed_datetime)

Time interval

Calculate the date of the time interval using timedelta

from datetime import date, timedelta
 
today = ()
future_date = today + timedelta(days=10)
print("Date after 10 days:", future_date)
 
past_date = today - timedelta(weeks=1)
print("Date one week ago:", past_date)

Calculate the date and time of the time interval

from datetime import datetime, timedelta
 
now = ()
 
future_time = now + timedelta(minutes=10)
print("Date time after 10 minutes:", future_time)
 
past_time = now - timedelta(hours=2)
print("Date time 2 hours ago:", past_time)

zoneinfo

Time conversion

After python 3.9, zoneinfo was introduced to handle time zones and can be directly used for datetime

from datetime import datetime
from zoneinfo import ZoneInfo
 
now_utc = (ZoneInfo("UTC"))
print("UTC Time:", now_utc)
 
# Convert to Beijing timenow_beijing = now_utc.astimezone(ZoneInfo("Asia/Shanghai"))
print("Beijing time:", now_beijing)
 
# Convert to New York timenow_newyork = now_utc.astimezone(ZoneInfo("America/New_York"))
print("New York Time:", now_newyork)

In fact, time conversion can also be calculated by yourself. For example, we have learned that Beijing time is UTC+8 and New York time is UTC-5.

from datetime import datetime, timedelta
 
now_utc = ()
print("UTC Time:", now_utc)
 
now_beijing = now_utc + timedelta(hours=8)
print("Beijing time:", now_beijing)
 
now_newyork = now_utc - timedelta(hours=5)
print("New York Time:", now_newyork)

List all time zones

All time zones

import zoneinfo
 
print(zoneinfo.available_timezones())

Traversal to find the Asia time zone

import zoneinfo
 
for zone in zoneinfo.available_timezones():
    if "Asia" in zone:
        print(zone)

Get time zone time

If you always set the local time zone time by yourself when using the current time, without relying on machine settings, you can get better cross-platformity

from datetime import datetime
from zoneinfo import ZoneInfo
 
tz_shanghai = ZoneInfo("Asia/Shanghai")
tz_newyork = ZoneInfo("America/New_York")
 
now_shanghai = (tz_shanghai)
now_newyork = (tz_newyork)
 
print("Beijing time:", now_shanghai)
print("New York Time:", now_newyork)

The above is a detailed explanation of how to correctly use timestamps, dates, time and time zones in Python. For more information about Python time, please follow my other related articles!