Bash: How to Convert Datetime to Epoch (With Example)


Often you may want to convert a datetime to epoch in Bash.

You can use the following syntax to do so:

date -d '05/30/2024 10:47:49' +"%s"

This particular example will convert the datetime 05/30/2024 10:47:49 into an epoch.

Note that in Linux, an epoch is the number of seconds that have elapsed since January 1, 1970.

We use the -d operator to specify that we would like to display the date described by the string that follows it using the format that follows the + sign.

By using +”%s” we are able to specify that we want to display the datetime in terms of number of seconds. 

The following example shows how to use this syntax in practice.

Related: How to Convert Epoch to Date in Bash

Example: How to Convert Datetime to Epoch in Bash

Suppose we would like to convert the datetime 05/30/2024 10:47:49 into an epoch.

We can use the following syntax to do so:

date -d '05/30/2024 10:47:49' +"%s"

The following screenshot shows how to use this syntax in practice:

Bash convert date to epoch

We can see that the the datetime 05/30/2024 10:47:49 has been converted to an epoch represented as:

  • 1717080469

This represents the total number of seconds that have elapsed since January 1, 1970.

Note that this example assumes that you’re passing a datetime that corresponds to your local time zone.

If you’d like to pass a UTC time instead, then you can use the -u flag as follows:

date -u -d '05/30/2024 10:47:49' +"%s"

This will return the number of seconds that have passed since January 1, 1970, assuming a UTC datetime is being used.

Feel free to use whichever method you prefer.

Related Tutorials

The following tutorials explain how to perform other common tasks in Bash:

How to Convert Timestamp to Date in Bash
How to Calculate Date Difference in Bash
How to Compare Dates in Bash

Leave a Reply