Python Tutorial (33) - Example: Converting a string time to a timestamp

Time: Column:Python views:230

Convert a Time String to a Timestamp in Python

In Python, you can convert a time string into a timestamp using the time module. Below is an example that demonstrates how to achieve this.

Example

import time

# Define the time string
a1 = "2019-5-10 23:40:00"

# First, convert the time string to a time struct
timeArray = time.strptime(a1, "%Y-%m-%d %H:%M:%S")

# Convert the time struct to a timestamp
timeStamp = int(time.mktime(timeArray))
print(timeStamp)

# Format conversion - change to another format using '/'
a2 = "2019/5/10 23:40:00"

# Convert the string to a time struct and then to another format
timeArray = time.strptime(a2, "%Y/%m/%d %H:%M:%S")
otherStyleTime = time.strftime("%Y/%m/%d %H:%M:%S", timeArray)
print(otherStyleTime)

Output:

1557502800
2019/05/10 23:40:00

Explanation:

  1. Convert Time String to Timestamp:

    • The function time.strptime() converts the time string into a time structure (timeArray).

    • The function time.mktime() is used to convert this time structure into a timestamp (seconds since January 1, 1970).

  2. Format Conversion:

    • The second example converts the date format from YYYY/MM/DD to a new format using time.strptime() and time.strftime() to reformat the date string.