- Timestamp To Date Converter
- Convert timestamp to date
- Convert date to timestamp
- How It Works
- Current Timestamp Examples
- Current Date and Time Examples
- Timestamp to Date Examples
- Parse Date to Timestamp Examples
- Unix Time
- How do I convert an epoch timestamp to a human readable format on the cli?
- 11 Answers 11
- How to convert timestamps to dates in Bash?
- 16 Answers 16
- Linux timestamp to time
- Get current time in seconds since the Epoch on Linux, Bash
- 7 Answers 7
- Pure bash solution
Timestamp To Date Converter
Convert timestamp to date or date to timestamp easily
Convert timestamp to date
Convert date to timestamp
How It Works
Timestamp Online is timestamp converver between unix timestamp and human readable form date. If you want to convert timestamp, it is sufficient to either enter your timestamp into input area, or you can construct URL with your timestamp — http://timestamp.online/timestamp/
Timestamp Online also supports countdown, so you can see, how much time remains to particular timestamp. URLs for countdowns have following form — http://timestamp.online/countdown/
Current Timestamp Examples
These examples are showing how to get current unix timestamp in seconds. These examples are returning timestamp in seconds, although some of the languages are returning timestamp in milliseconds.
Current Date and Time Examples
These examples are showing how to get current date and time that could be presented to the end-user.
Timestamp to Date Examples
These examples are showing how to convert timestamp — either in milliseconds or seconds to human readable form.
Parse Date to Timestamp Examples
These examples are showing how to parse date in human readable form to unix timestamp in either milliseconds or seconds.
Unix Time
Unix time (also known as POSIX time or Epoch time) is a system for describing instants in time, defined as the number of seconds that have elapsed since 00:00:00 Coordinated Universal Time (UTC), Thursday, 1 January 1970, not counting leap seconds. It is used widely in Unix-like and many other operating systems and file formats. Because it does not handle leap seconds, it is neither a linear representation of time nor a true representation of UTC.
Источник
How do I convert an epoch timestamp to a human readable format on the cli?
How do I convert an epoch timestamp to a human readable format on the cli? I think there’s a way to do it with date but the syntax eludes me (other ways welcome).
11 Answers 11
On Linux (specifically, with GNU coreutils ≥5.3):
With older versions of GNU date, you can calculate the relative difference to the UTC epoch:
If you need portability, you’re out of luck. The only time you can format with a POSIX shell command (without doing the calculation yourself) line is the current time. In practice, Perl is often available:
date -d @1190000000 Replace 1190000000 with your epoch
If your epoch time is in milliseconds instead of seconds, remove the last three digits before passing it to date -d :
This gives incorrect data. Remove the last three digits.
Custom format with GNU date :
Or with GNU awk :
With bash-4.2 or above:
(where %F %T is the strftime() -type format)
That syntax is inspired from ksh93 .
In ksh93 however, the argument is taken as a date expression where various and hardly documented formats are supported.
For a Unix epoch time, the syntax in ksh93 is:
ksh93 however seems to use its own algorithm for the timezone and can get it wrong. For instance, in Britain, it was summer time all year in 1970, but:
Источник
How to convert timestamps to dates in Bash?
I need a shell command or script that converts a Unix timestamp to a date. The input can come either from the first parameter or from stdin, allowing for the following usage patterns:
Both commands should output «Wed Mar 3 13:38:49 2010».
16 Answers 16
On later versions of common Linux distributions you can use:
works for me on Mac OS X.
% date —help | grep — -r -r, —reference=FILE display the last modification time of FILE
This version is similar to chiborg’s answer, but it eliminates the need for the external tty and cat . It uses date , but could just as easily use gawk . You can change the shebang and replace the double square brackets with single ones and this will also run in sh .
You can use GNU date, for example,
You can use this simple awk script:
Since Bash 4.2 you can use printf ‘s %(datefmt)T format:
That’s nice, because it’s a shell builtin. The format for datefmt is a string accepted by strftime(3) (see man 3 strftime ). Here %c is:
%c The preferred date and time representation for the current locale.
Now if you want a script that accepts an argument and, if none is provided, reads stdin, you can proceed as:
You can get formatted date from timestamp like this
I use this when converting log files or monitoring them:
In OSX, or BSD, there’s an equivalent -r flag which apparently takes a unix timestamp. Here’s an example that runs date four times: once for the first date, to show what it is; one for the conversion to unix timestamp with %s , and finally, one which, with -r , converts what %s provides back to a string.
Источник
Linux timestamp to time
Что такое Unix время или Unix эпоха (Unix epoch или Unix time или POSIX time или Unix timestamp) ?
UNIX-время или POSIX-время (англ. Unix time) — способ кодирования времени, принятый в UNIX и других POSIX-совместимых операционных системах.
Моментом начала отсчёта считается полночь (по UTC) с 31 декабря 1969 года на 1 января 1970, время с этого момента называют «эрой UNIX» (англ. Unix Epoch).
Время UNIX согласуется с UTC, в частности, при объявлении високосных секунд UTC соответствующие номера секунд повторяются.
Способ хранения времени в виде количества секунд очень удобно использовать при сравнении дат (с точностью до секунды), а также для хранения дат: при необходимости их можно преобразовать в любой удобочитаемый формат. Дата и время в этом формате также занимают очень мало места (4 или 8 байтов, в зависимости от размера машинного слова), поэтому его разумно использовать для хранения больших объёмов дат. Недостатки в производительности могут проявиться при очень частом обращении к элементам даты, вроде номера месяца и т. п. Но в большинстве случаев эффективнее хранить время в виде одной величины, а не набора полей.
Обычная дата(Human readable time) | Секунды |
1 минута | 60 секунд |
1 час | 3600 секунд |
1 день | 86400 секунд |
1 неделя | 604800 секунд |
1 месяц (30.44 дней) | 2629743 секунд |
1 год (365.24 дней) | 31556926 секунд |
Конвертивание эпохи Unix в человекопонятную дату(human readable date)
Unix дата начала и конца года, месяца или дня
Перевод секунд в дни, часы и минуты
Как получить Unix время в.
Perl | time |
PHP | time() |
Ruby | Time.now (или Time.new ). Чтобы вывести: Time.now.to_i |
Python | import time сначала, потом time.time() |
Java | long epoch = System.currentTimeMillis()/1000; |
Microsoft .NET C# | epoch = (DateTime.Now.ToUniversalTime().Ticks — 621355968000000000) / 10000000; |
VBScript/ASP | DateDiff(«s», «01/01/1970 00:00:00», Now()) |
Erlang | calendar:datetime_to_gregorian_seconds(calendar:now_to_universal_time( now()))-719528*24*3600. |
MySQL | SELECT unix_timestamp(now()) |
PostgreSQL | SELECT extract(epoch FROM now()); |
SQL Server | SELECT DATEDIFF(s, ‘1970-01-01 00:00:00’, GETUTCDATE()) |
JavaScript | Math.round(new Date().getTime()/1000.0) getTime() возвращает время в миллисекундах. |
Unix/Linux | date +%s |
Другие OS | Командная строка: perl -e «print time» (Если Perl установлен на вашей системе) |
Конвертирование даты в Unix время в.
PHP | mktime(часы, минуты, секунды, месяц, день, год) |
Ruby | Time.local(год, месяц, день, часы, минуты, секунды, usec ) (или Time.gm для GMT/UTC вывода). Чтобы вывести добавьте .to_i |
Python | import time сначала, потом int(time.mktime(time.strptime(‘2000-01-01 12:34:00’, ‘%Y-%m-%d %H:%M:%S’))) |
Java | long epoch = new java.text.SimpleDateFormat («dd/MM/yyyy HH:mm:ss»).parse(«01/01/1970 01:00:00»); |
VBScript/ASP | DateDiff(«s», «01/01/1970 00:00:00», поле даты) |
MySQL | SELECT unix_timestamp(время) Формат времени: YYYY-MM-DD HH:MM:SS или YYMMDD или YYYYMMDD |
PostgreSQL | SELECT extract(epoch FROM date(‘2000-01-01 12:34’)); С timestamp: SELECT EXTRACT(EPOCH FROM TIMESTAMP WITH TIME ZONE ‘2001-02-16 20:38:40-08’); C интервалом: SELECT EXTRACT(EPOCH FROM INTERVAL ‘5 days 3 hours’); |
SQL Server | SELECT DATEDIFF(s, ‘1970-01-01 00:00:00’, поле с датой) |
Unix/Linux | date +%s -d»Jan 1, 1980 00:00:01″ |
Конвертирование Unix времеми в понятную дату(human readable date).
PHP | date(Формат, unix время); |
Ruby | Time.at(unix время) |
Python | import time сначала, потом time.strftime(«%a, %d %b %Y %H:%M:%S +0000», time.localtime(unix время)) Замените time.localtime на time.gmtime для GMT даты. |
Java | String date = new java.text.SimpleDateFormat(«dd/MM/yyyy HH:mm:ss»).format(new java.util.Date (unix время*1000)); |
VBScript/ASP | DateAdd(«s», unix время, «01/01/1970 00:00:00») |
PostgreSQL | SELECT TIMESTAMP WITH TIME ZONE ‘epoch’ + unix время * INTERVAL ‘1 second’; |
MySQL | from_unixtime(unix время, не обязательно, выходной формат) Стандартный формат выхода YYY-MM-DD HH:MM:SS |
SQL Server | DATEADD(s, unix время, ‘1970-01-01 00:00:00’) |
Microsoft Excel | =(A1 / 86400) + 25569 Результат будет в GMT зоне времени. Для других временных зон: =((A1 +/- разница аремени для зоны) / 86400) + 25569. |
Linux | date -d @1190000000 |
Другие OS | Командная строка: perl -e «print scalar(localtime(unix время))» (Если установлен Perl) Замените ‘localtime’ на ‘gmtime’ для GMT/UTC зоны времени. |
Для чего нужен инструмент «Unixtime конвертер»?
Данный инструмент, в первую очередь, будет полезен веб-мастерам, которые постоянно имеют дело с большими объемами дат или часто в своей работе обращаются к их элементам. С помощью инструмента «Unixtime конвертер» можно легко конвертировать Unix время в понятную для пользователя дату (и наоборот), узнать текущее Unix epoch время, а также получить Unix время в различных языках программирования, СУБД и операционных системах.
Что такое Unix время?
Эра Unix (Unix epoch) началась в ночь с 31 декабря 1969 года на 1 января 1970 года. Именно эту дату взяли за точку отсчета «компьютерного» времени, которое исчисляется в секундах и занимает очень мало места на диске – всего 4 или 8 байт. С помощью такого способа кодирования программисты могут «спрятать» любую дату в одно число, и легко конвертировать его обратно в понятный пользователям формат.
Unix время (еще его называют Unix time или POSIX time) удобно использовать в различных операционных системах и языках программирования, так как оно отображается в виде одной величины, а не определенного количества полей, занимающих место. К тому же, UNIX time полностью соответствует стандарту UTC (в том числе и в високосных годах) – в таком случае соответствующие значения секунд просто повторяются.
Пару слов о терминах.
Итак, Unix-временем (или POSIX-временем) считается количество секунд, которые прошли с полуночи 1 января 1970 года до настоящего времени.
Unix Timestamp (временная метка) – это «зафиксированное» время, иными словами – конкретная дата, запечатленная в числе.
UTC (Universal Coordinated Time) – это Всемирное координированное время, которое «фиксируется» на нулевом меридиане, и от которого ведется отсчет географических часовых поясов.
Насколько «долговечна» данная система?
Всего лишь через пару десятков лет, а именно 19 января 2038 года в 03:14:08 по UTC Unix time достигнет значения 2147483648, и компьютерные системы могут интерпретировать это число как отрицательное. Ключ к решению данной проблемы лежит в использовании 64-битной (вместо 32-битной) переменной для хранения времени. В таком случае, запаса числовых значений Unix time хватит человечеству еще на 292 миллиарда лет. Неплохо, правда?
Unix время – одно для всех
Если вы живете в Лондоне или Сан-Франциско, а ваши друзья – в Москве, то «сверить часы» можно по Unix time: эта система в данный момент времени едина для всего мира. Естественно, если время на серверах выставлено правильно. А с помощью инструмента «Unixtime конвертер» такая конвертация займет у вас доли секунды.
Источник
Get current time in seconds since the Epoch on Linux, Bash
I need something simple like date , but in seconds since 1970 instead of the current date, hours, minutes, and seconds.
date doesn’t seem to offer that option. Is there an easy way?
7 Answers 7
This should work:
Get the seconds since epoch(Jan 1 1970) for any given date(e.g Oct 21 1973).
Convert the number of seconds back to date
The command date is pretty versatile. Another cool thing you can do with date(shamelessly copied from date —help ). Show the local time for 9AM next Friday on the west coast of the US
So far, all the answers use the external program date .
Since Bash 4.2, printf has a new modifier %(dateformat)T that, when used with argument -1 outputs the current date with format given by dateformat , handled by strftime(3) ( man 3 strftime for informations about the formats).
So, for a pure Bash solution:
or if you need to store the result in a variable var :
No external programs and no subshells!
Since Bash 4.3, it’s even possible to not specify the -1 :
(but it might be wiser to always give the argument -1 nonetheless).
If you use -2 as argument instead of -1 , Bash will use the time the shell was started instead of the current date. This can be used to compute elapsed times
Pure bash solution
Since bash 5.0 (released on 7 Jan 2019) you can use the built-in variable EPOCHSECONDS .
There is also EPOCHREALTIME which includes fractions of seconds.
EPOCHREALTIME can be converted to micro-seconds (μs) by removing the decimal point. This might be of interest when using bash ‘s built-in arithmetic (( expression )) which can only handle integers.
In all examples from above the printed time values are equal for better readability. In reality the time values would differ since each command takes a small amount of time to be executed.
With most Awk implementations:
This is an extension to what @pellucide has done, but for Macs:
To determine the number of seconds since epoch (Jan 1 1970) for any given date (e.g. Oct 21 1973)
Please note, that for completeness, I have added the time part to the format. The reason being is that date will take whatever date part you gave it and add the current time to the value provided. For example, if you execute the above command at 4:19PM, without the ’00:00:00′ part, it will add the time automatically. Such that «Oct 21 1973» will be parsed as «Oct 21 1973 16:19:00». That may not be what you want.
Источник