Python Convert Timestamp to Specified Format Date

Document 对象参考手册Python3 Examples

Given a timestamp, convert it to a time in the specified format.

Pay attention to the timezone settings.

Explanation of common formatting codes

  • %Y- Four-digit year (2024)
  • %y- Two-digit year (24)
  • %m- Month (01-12)
  • %d- Day (01-31)
  • %H- Hour in 24-hour format (00-23)
  • %I- Hour in 12-hour format (01-12)
  • %M- Minute (00-59)
  • %S- Second (00-59)
  • %p - AM/PM
  • %A- Full weekday name (Monday)
  • %a- Abbreviated weekday name (Mon)
  • %B- Full month name (January)
  • %b- Abbreviated month name (Jan)

Current time

Example 1

import time # Get the current timestamp now = int(time.time()) # Convert to other date formats, e.g. "%Y-%m-%d %H:%M:%S" timeArray = time.localtime(now) otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray) print(otherStyleTime)

Executing the above code produces the following output:

2019-05-21 18:02:49

Example 2

import datetime # Get the current time now = datetime.datetime.now() # Convert to the specified format otherStyleTime = now.strftime("%Y-%m-%d %H:%M:%S") print(otherStyleTime)

Executing the above code produces the following output:

2019-05-21 18:03:48

Specified timestamp

Example 3

import time timeStamp = 1557502800 timeArray = time.localtime(timeStamp) otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray) print(otherStyleTime)

Executing the above code produces the following output:

2019-05-10 23:40:00

Output dates in different formats:

Example 4

import datetime

timestamp = 1710000000
dt_object = datetime.datetime.fromtimestamp(timestamp)

# Format 1: YYYY-MM-DD
print(dt_object.strftime("%Y-%m-%d"))  # Output: 2024-03-09

# Format 2: MM/DD/YYYY
print(dt_object.strftime("%m/%d/%Y"))  # Output: 03/09/2024

# Format 3: With full weekday and month name
print(dt_object.strftime("%A, %B %d, %Y"))  # Output: Saturday, March 09, 2024

Complete example (including timezone handling):

Example 5

from datetime import datetime, timezone

# Millisecond-level timestamp (e.g., JavaScript's Date.now())
timestamp_ms = 1710000000000

# Convert to seconds and convert to UTC time
timestamp_s = timestamp_ms / 1000
dt_utc = datetime.fromtimestamp(timestamp_s, tz=timezone.utc)

# Format as UTC time string
formatted_utc = dt_utc.strftime("%Y-%m-%d %H:%M:%S UTC")
print(formatted_utc)  # Output: 2024-03-09 00:00:00 UTC

# Convert to local time
dt_local = datetime.fromtimestamp(timestamp_s)
formatted_local = dt_local.strftime("%Y-%m-%d %H:%M:%S %Z")
print(formatted_local)  # Output depends on your timezone, e.g., 2024-03-08 16:00:00 PST

The output is:

2024-03-09 16:00:00 UTC
2024-03-10 00:00:00 

Document 对象参考手册Python3 Examples

Other Extensions