Python Convert Date String to Epoch

1. Introduction

Converting date strings to epoch time, which represents the number of seconds since January 1, 1970, known as the Unix epoch, is a common task in programming. It's especially relevant when working with timestamps in various data storage or processing applications. In Python, this can be achieved with the standard datetime module. This blog post will demonstrate how to convert a date string into epoch time in Python.

Definition

Epoch time, or Unix time, is a system for describing a point in time as the number of seconds that have elapsed since 00:00:00 UTC on 1 January 1970. To convert a date string to epoch time in Python, we first parse the date string into a datetime object and then convert this object into the corresponding number of seconds since the Unix epoch.

2. Program Steps

1. Import the datetime module to handle date and time operations.

2. Define the date string and its format.

3. Parse the date string into a datetime object using strptime.

4. Convert the datetime object to epoch time.

5. Output the epoch time.

3. Code Program

# Step 1: Import the datetime module
from datetime import datetime

# Step 2: Define the date string and its format
date_string = "2023-11-02 00:00:00"
date_format = "%Y-%m-%d %H:%M:%S"

# Step 3: Parse the date string into a datetime object
datetime_obj = datetime.strptime(date_string, date_format)

# Step 4: Convert the datetime object to epoch time
epoch_time = int(datetime_obj.timestamp())

# Step 5: Print the epoch time
print(epoch_time)

Output:

1667347200

Explanation:

1. The datetime module provides functions and classes for working with dates and times.

2. date_string is a string representing a specific point in time, and date_format is the corresponding format that explains how to interpret date_string.

3. datetime_obj is the datetime object created by parsing date_string with the strptime method.

4. epoch_time is calculated from datetime_obj using the timestamp() method, which is then converted to an integer to represent the epoch time.

5. The output is epoch_time, displaying the number of seconds from date_string to the Unix epoch.


Comments