Get UTC time in seconds

BashDateDatetime

Bash Problem Overview


It looks like I can't manage to get the bash UTC date in second. I'm in Sydney so + 10hours UTC time

 date
 Thu Jul 3 17:28:19 WST 2014

 date -u
 Thu Jul 3 07:28:20 UTC 2014

But when I tried to convert it, I'm getting the same result which is not UTC time

 date +%s
 1404372514

 date -u +%s
 1404372515

What am I missing here?


After getting an answer saying date +%s was returning UTC time, here are more details about the problem I'm facing now.

I'm trying to compare a date written in a file with python. This date is written in seconds in UTC time. And the bash date +%s doesn't give me the same one. Actually if I'm doing in python time.asctime(time.localtime(date_in_seconds_from_bash)), I get the current time of Sydney, not UTC. I don't understand.

Bash Solutions


Solution 1 - Bash

I believe +%s is seconds since epoch. It's timezone invariant.

Solution 2 - Bash

I bet this is what was intended as a result.

$ date -u --date=@1404372514
Thu Jul  3 07:28:34 UTC 2014

Solution 3 - Bash

You say you're using:

time.asctime(time.localtime(date_in_seconds_from_bash))

where date_in_seconds_from_bash is presumably the output of date +%s.

The time.localtime function, as the name implies, gives you local time.

If you want UTC, use time.gmtime() rather than time.localtime().

As JamesNoonan33's answer says, the output of date +%s is timezone invariant, so date +%s is exactly equivalent to date -u +%s. It prints the number of seconds since the "epoch", which is 1970-01-01 00:00:00 UTC. The output you show in your question is entirely consistent with that:

date -u
Thu Jul 3 07:28:20 UTC 2014

date +%s
1404372514   # 14 seconds after "date -u" command

date -u +%s
1404372515   # 15 seconds after "date -u" command

Solution 4 - Bash

One might consider adding this line to ~/.bash_profile (or similar) in order to can quickly get the current UTC both as current time and as seconds since the epoch.

alias utc='date -u && date -u +%s'

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRomanzo CriminaleView Question on Stackoverflow
Solution 1 - BashJamesNoonan33View Answer on Stackoverflow
Solution 2 - BashDerek BoonstraView Answer on Stackoverflow
Solution 3 - BashKeith ThompsonView Answer on Stackoverflow
Solution 4 - BashAdamView Answer on Stackoverflow