136

The date time string is in the following format: 06/12/2012 07:21:22. How can I convert it to UNIX timestamp or epoch?

codeforester
  • 39,467
  • 16
  • 112
  • 140
Edward D.
  • 1,431
  • 3
  • 11
  • 5

6 Answers6

125

What you're looking for is date --date='06/12/2012 07:21:22' +"%s". Keep in mind that this assumes you're using GNU coreutils, as both --date and the %s format string are GNU extensions. POSIX doesn't specify either of those, so there is no portable way of making such conversion even on POSIX compliant systems.

Consult the appropriate manual page for other versions of date.

Note: bash --date and -d option expects the date in US or ISO8601 format, i.e. mm/dd/yyyy or yyyy-mm-dd, not in UK, EU, or any other format.

SEoF
  • 1,092
  • 14
  • 26
Daniel Kamil Kozar
  • 18,476
  • 5
  • 50
  • 64
  • 12
    I get 'date: illegal option --' when I run on Mac OSX 10.8.2 – Ben Clayton Feb 11 '13 at 15:22
  • 9
    For noobs like me `+"%s"` stands for output format and `%s` is the format of time in seconds since 1970 – razz Jun 18 '15 at 03:01
  • 5
    Note: if you want to specify the time in another timezone (like UTC) add -HHMM or +HHMM to the end. So `date --date='06/12/2012 07:21:22 -0000' +"%s"` converts UTC date to unix time stamp – Greg Bray Oct 16 '18 at 00:58
  • 2
    For GNU date, if you wish to use UTC note that the format is `yyyy-mm-dd hh:mm:ss`have a look at https://www.gnu.org/software/coreutils/manual/html_node/Examples-of-date.html : `gdate --date='2019-06-18 00:02:00 +0000' +%s` – Ashutosh Jindal Jun 18 '19 at 11:29
  • doesn't work on a Mac... I wonder if there is a way to work both on a Mac and Linux – nonopolarity Jan 28 '20 at 16:49
  • @nonopolarity You can [install GNU utilities on a mac](https://apple.stackexchange.com/a/69332/42929), then it'll work. A number of other GNU utilities are handy too (eg: gnu grep, which accepts perl regexes) – drevicko May 08 '20 at 01:54
  • @nonopolarity On my mac with gnu coreutils, the command is called `gdate` instead of date. I can run the above command from @Daniel Kamil Kozar using: ```gdate --date='06/12/2012 07:21:22' +"%s"``` which in turn gives me: `1339510882` – Joseph Ishak Dec 01 '20 at 00:26
  • @Ben Clayton and others: on macOS, you can use `date -j -f %Y-%m-%d 2022-09-27 +%s` – luckman212 Sep 27 '22 at 20:45
82

For Linux, run this command:

date -d '06/12/2012 07:21:22' +"%s"

For macOS, run this command:

date -jf "%Y-%m-%d %H:%M:%S" "1970-01-01 00:00:00" +%s
Chris F Carroll
  • 11,146
  • 3
  • 53
  • 61
Abdul Rehman Janjua
  • 1,461
  • 14
  • 19
  • 1
    On OSX the timestamp increases somehow with the current time. I currently don't have an explanation for that... – polym Sep 22 '15 at 22:20
  • 3
    Update: That was because it adjusts the timestamp for my localtime I guess... Adding a `-u` flag should fix that. – polym Sep 24 '15 at 10:57
  • 1
    @AbdulRehmanJanjua The `-u` flag should come **before** the `-f` flag, or else the shell interprets it the format string. So, it should be: `date -j -u -f "%a..."` –  Dec 31 '15 at 13:43
  • So, why doesn't `echo date -d '06/12/2012 07:21:22' +"%s"` output the date? – Sandeepan Nath Oct 07 '16 at 09:26
  • What if my time is in format `14. 10. 2016 20:22:57`, date says invalid time. – Youda008 Oct 27 '16 at 11:12
  • 11
    Pasting exactly that in a macOS terminal fails. – zneak Aug 28 '17 at 17:13
  • 20
    `date -jf "%Y-%m-%d %H:%M:%S" "2018-01-08 14:45:00" +%s` – daviestar Jan 08 '18 at 14:55
  • 1
    It fails with the `-u` option because that affects both input an output formats, and a format with `EDT` clearly is not UTF. Use `-u` if you are not specifying a timezone in your input. Epoch second (`%s`) does not use timezones. – ghoti Sep 21 '22 at 17:57
16

A lot of these answers overly complicated and also missing how to use variables. This is how you would do it more simply on standard Linux system (as previously mentioned the date command would have to be adjusted for Mac Users) :

Sample script:

#!/bin/bash
orig="Apr 28 07:50:01"
epoch=$(date -d "${orig}" +"%s")
epoch_to_date=$(date -d @$epoch +%Y%m%d_%H%M%S)    

echo "RESULTS:"
echo "original = $orig"
echo "epoch conv = $epoch"
echo "epoch to human readable time stamp = $epoch_to_date"

Results in :

RESULTS:
original = Apr 28 07:50:01
epoch conv = 1524916201 
epoch to human readable time stamp = 20180428_075001

Or as a function :

# -- Converts from human to epoch or epoch to human, specifically "Apr 28 07:50:01" human.
#    typeset now=$(date +"%s")
#    typeset now_human_date=$(convert_cron_time "human" "$now")

function convert_cron_time() {
    case "${1,,}" in
        epoch)
            # human to epoch (eg. "Apr 28 07:50:01" to 1524916201)
            echo $(date -d "${2}" +"%s")
            ;;
        human)
            # epoch to human (eg. 1524916201 to "Apr 28 07:50:01")
            echo $(date -d "@${2}" +"%b %d %H:%M:%S")
            ;;
    esac
}
Mike Q
  • 6,716
  • 5
  • 55
  • 62
8

Just be sure what timezone you want to use.

datetime="06/12/2012 07:21:22"

Most popular use takes machine timezone.

date -d "$datetime" +"%s" #depends on local timezone, my output = "1339456882"

But in case you intentionally want to pass UTC datetime and you want proper timezone you need to add -u flag. Otherwise you convert it from your local timezone.

date -u -d "$datetime" +"%s" #general output = "1339485682"
Jsowa
  • 9,104
  • 5
  • 56
  • 60
5

Efficient way to convert date time string to epoch in bash

Avoiding useless repetitives forks, in order to make this translation a lot quicker...

Instead of running 1 fork for each translation, we could run date -f - +%s as background process...

Intro

Common syntax:

epochDate=$(date -d "$InputDate" +%s)

Work fine, but become heavy if run repetetively!

In this post, you will find

  • a Quick Demo, following this,
  • some Explanations,
  • a Function useable for many Un*x tools (bc, rot13, sed...).

Quick Demo

fifo=$HOME/.fifoDate-$$
mkfifo $fifo
exec 5> >(exec stdbuf -o0 date -f - +%s >$fifo 2>&1)
echo now 1>&5
exec 6< $fifo
rm $fifo
read -t 1 -u 6 now
echo $now

This must output current UNIXTIME. From there, you could compare

time for i in {1..5000};do echo >&5 "now" ; read -t 1 -u6 ans;done
real    0m0.298s
user    0m0.132s
sys     0m0.096s

and:

time for i in {1..5000};do ans=$(date +%s -d "now");done 
real    0m6.826s
user    0m0.256s
sys     0m1.364s

From more than 6 seconds to less than a half second!!(on my host).

You could check echo $ans, replace "now" by "2019-25-12 20:10:00" and so on...

Optionaly, you could, once requirement of date subprocess ended:

exec 5>&- ; exec 6<&-

Original post (detailed explanation)

Instead of running 1 fork by date to convert, run date just 1 time and do all convertion with same process (this could become a lot quicker)!:

date -f - +%s <<eof
Apr 17  2014
May 21  2012
Mar  8 00:07
Feb 11 00:09
eof
1397685600
1337551200
1520464020
1518304140

Sample:

start1=$(LANG=C ps ho lstart 1)
start2=$(LANG=C ps ho lstart $$)
dirchg=$(LANG=C date -r .)
read -p "A date: " userdate
{ read start1 ; read start2 ; read dirchg ; read userdate ;} < <(
   date -f - +%s <<<"$start1"$'\n'"$start2"$'\n'"$dirchg"$'\n'"$userdate" )

Then now have a look:

declare -p start1 start2 dirchg userdate

(may answer something like:

declare -- start1="1518549549"
declare -- start2="1520183716"
declare -- dirchg="1520601919"
declare -- userdate="1397685600"

This was done in one execution!

Using long running subprocess

We just need one fifo:

mkfifo /tmp/myDateFifo
exec 7> >(exec stdbuf -o0 /bin/date -f - +%s >/tmp/myDateFifo)
exec 8</tmp/myDateFifo
rm /tmp/myDateFifo

(Note: As process is running and all descriptors are opened, we could safely remove fifo's filesystem entry.)

Then now:

LANG=C ps ho lstart 1 $$ >&7
read -u 8 start1
read -u 8 start2
LANG=C date -r . >&7
read -u 8 dirchg

read -p "Some date: " userdate
echo >&7 $userdate
read -u 8 userdate

We could buid a little function:

mydate() {
    local var=$1;
    shift;
    echo >&7 $@
    read -u 8 $var
}

mydate start1 $(LANG=C ps ho lstart 1)
echo $start1

Or use my newConnector function

With functions for connecting MySQL/MariaDB, PostgreSQL and SQLite...

You may find them in different version on GitHub, or on my site: download or show.

wget https://raw.githubusercontent.com/F-Hauri/Connector-bash/master/shell_connector.bash

. shell_connector.bash 
newConnector /bin/date '-f - +%s' @0 0

myDate "2018-1-1 12:00" test
echo $test
1514804400

Nota: On GitHub, functions and test are separated files. On my site test are run simply if this script is not sourced.

# Exit here if script is sourced
[ "$0" = "$BASH_SOURCE" ] || { true;return 0;}
F. Hauri - Give Up GitHub
  • 64,122
  • 17
  • 116
  • 137
4
get_curr_date () {
    # get unix time
    DATE=$(date +%s)
    echo "DATE_CURR : "$DATE
}

conv_utime_hread () {
    # convert unix time to human readable format
    DATE_HREAD=$(date -d @$DATE +%Y%m%d_%H%M%S)
    echo "DATE_HREAD          : "$DATE_HREAD
}
sschuberth
  • 28,386
  • 6
  • 101
  • 146
shgurbanov
  • 49
  • 3