Перевод даты в unixtime excel

Временная метка Unix также называется временем эпохи или временем POSIX, которое широко используется во многих операционных системах или форматах файлов. В этом руководстве рассказывается о преобразовании между датой и меткой времени Unix в Excel.

Преобразовать дату в метку времени

Преобразование даты и времени в метку времени

Преобразовать метку времени на дату

Дополнительные руководства по преобразованию даты и времени …


стрелка синий правый пузырь Преобразовать дату в метку времени

Чтобы преобразовать дату в метку времени, формула может вычислить это.

Выберите пустую ячейку, предположим, ячейку C2, и введите эту формулу = (C2-ДАТА (1970,1,1)) * 86400 в это и нажмите Enter key, при необходимости вы можете применить диапазон с этой формулой, перетащив маркер автозаполнения. Теперь диапазон ячеек даты преобразован в метки времени Unix.
документ-конвертировать-дата-unix-1


время конвертации документов 1


стрелка синий правый пузырь Преобразование даты и времени в метку времени

Существует формула, которая может помочь вам преобразовать дату и время в метку времени Unix.

1. Во-первых, вам нужно ввести всемирное координированное время в ячейку, 1. Смотрите скриншот:
документ-конвертировать-дата-unix-2

2. Затем введите эту формулу = (A1- $ C $ 1) * 86400 в ячейку, нажмите Enter , а затем при необходимости перетащите дескриптор автозаполнения в диапазон с этой формулой. Смотрите скриншот:
документ-конвертировать-дата-unix-3

Tips: В формуле A1 — это ячейка даты и времени, C1 — введенная вами координата всемирного времени.


стрелка синий правый пузырь Преобразовать метку времени на дату

Если у вас есть список временных меток, необходимых для преобразования на сегодняшний день, вы можете сделать следующие шаги:

1. В пустой ячейке рядом со списком временных меток введите эту формулу. =(((A1/60)/60)/24)+DATE(1970,1,1), нажмите Enter и перетащите маркер автозаполнения в нужный диапазон.
документ-конвертировать-дата-unix-4

2. Затем щелкните правой кнопкой мыши ячейки, в которых используется формула, и выберите Формат ячеек из контекстного меню, затем во всплывающем Формат ячеек диалог под Nвокруг вкладку нажмите Время в Категория список, затем выберите тип даты в правом разделе.
документ-конвертировать-дата-unix-5

3. Нажмите OK, теперь вы можете видеть, что метки времени Unix преобразованы в даты.
документ-конвертировать-дата-unix-6

Ноты:

1. A1 указывает нужную ячейку с отметкой времени.

2. Эту формулу также можно использовать для преобразования ряда временных меток в дату и время, просто отформатируйте результат в формате даты и времени.

3. Приведенная выше формула преобразует 10-значное число в стандартную дату и время. Если вы хотите преобразовать 11-значное число, 13-значное число или 16-значное число в стандартную дату и время в Excel, используйте формулу, как показано ниже:

Преобразование 11-значного числа в дату: =A1/864000+ДАТА(1970,1,1)

Преобразование 13-значного числа в дату: =A1/86400000+ДАТА(1970,1,1)

Преобразование 16-значного числа в дату: =A1/86400000000+ДАТА(1970,1,1)

Для разной длины числа, которое необходимо преобразовать в дату и время, просто измените количество нулей делителя в формуле, чтобы правильно получить результат.


Относительные статьи:

  • Как преобразовать дату и время из одного часового пояса в другой в Excel?
    Эта статья покажет вам, как преобразовать дату и время из одного часового пояса в другой в Excel.

  • Как разделить дату и время из ячейки на две отдельные ячейки в Excel?
    Например, у вас есть список данных, смешанных с датой и временем, и вы хотите разделить каждую из них на две ячейки, одна — это дата, а другая — время, как показано ниже. В этой статье представлены два быстрых метода решения этой проблемы в Excel.

  • Как преобразовать ячейку формата даты / времени в дату только в Excel?
    Если вы хотите преобразовать ячейку формата даты и времени только в значение даты, такое как 2016/4/7 1:01 AM до 2016/4/7, эта статья может вам помочь.

  • Как убрать время с даты в Excel?
    Если есть столбец даты с отметкой времени, например, 2 17:2012, и вы не хотите сохранять отметку времени и хотите удалить время 12:23 из даты и оставить только дату 12. Как можно быстро удалить время из даты в нескольких ячейках Excel?

  • Как объединить дату и время в одну ячейку в Excel?
    На листе есть два столбца, один — это дата, другой — время. Есть ли способ быстро объединить эти два столбца в один и сохранить формат времени? Теперь в этой статье представлены два способа в Excel объединить столбец даты и столбца времени в один и сохранить формат времени.


Лучшие инструменты для работы в офисе

Kutools for Excel Решит большинство ваших проблем и повысит вашу производительность на 80%

  • Снова использовать: Быстро вставить сложные формулы, диаграммы и все, что вы использовали раньше; Зашифровать ячейки с паролем; Создать список рассылки и отправлять электронные письма …
  • Бар Супер Формулы (легко редактировать несколько строк текста и формул); Макет для чтения (легко читать и редактировать большое количество ячеек); Вставить в отфильтрованный диапазон
  • Объединить ячейки / строки / столбцы без потери данных; Разделить содержимое ячеек; Объединить повторяющиеся строки / столбцы… Предотвращение дублирования ячеек; Сравнить диапазоны
  • Выберите Дубликат или Уникальный Ряды; Выбрать пустые строки (все ячейки пустые); Супер находка и нечеткая находка во многих рабочих тетрадях; Случайный выбор …
  • Точная копия Несколько ячеек без изменения ссылки на формулу; Автоматическое создание ссылок на несколько листов; Вставить пули, Флажки и многое другое …
  • Извлечь текст, Добавить текст, Удалить по позиции, Удалить пробел; Создание и печать промежуточных итогов по страницам; Преобразование содержимого ячеек в комментарии
  • Суперфильтр (сохранять и применять схемы фильтров к другим листам); Расширенная сортировка по месяцам / неделям / дням, периодичности и др .; Специальный фильтр жирным, курсивом …
  • Комбинируйте книги и рабочие листы; Объединить таблицы на основе ключевых столбцов; Разделить данные на несколько листов; Пакетное преобразование xls, xlsx и PDF
  • Более 300 мощных функций. Поддерживает Office/Excel 2007-2021 и 365. Поддерживает все языки. Простое развертывание на вашем предприятии или в организации. Полнофункциональная 30-дневная бесплатная пробная версия. 60-дневная гарантия возврата денег.

вкладка kte 201905


Вкладка Office: интерфейс с вкладками в Office и упрощение работы

  • Включение редактирования и чтения с вкладками в Word, Excel, PowerPoint, Издатель, доступ, Visio и проект.
  • Открывайте и создавайте несколько документов на новых вкладках одного окна, а не в новых окнах.
  • Повышает вашу продуктивность на 50% и сокращает количество щелчков мышью на сотни каждый день!

офисный дно

Содержание

  • Что такое Unix Time
  • Преобразование времени Excel в время Unix
  • Преобразование времени Unix в время Excel
  • Преобразование времени Excel в время Unix в Google Таблицах

Скачать пример рабочей книги

Загрузите образец книги

В этом руководстве будет показано, как преобразовать время в формате Excel в время Unix в Excel и Google Таблицах.

Что такое Unix Time

Время Unix также известно как время эпохи, время POSIX или временная метка Unix. Это система, которая считает количество секунд, прошедших с эпохи Unix, т. Е. 1 января.ул, 1970. Проще говоря, время Unix — это общее количество секунд между датой и эпохой Unix.

Чтобы рассчитать время Unix, сначала нам нужно найти общее количество дней между временем Excel и временем эпохи. Затем умножьте вычисленные дни на 86 400, потому что в сутках 86 400 секунд (24 часа × 60 минут × 60 секунд = 86 400 секунд).

1 = (B5-ДАТА (1970,1,1)) * 86400

Пошаговое объяснение

Первым шагом в преобразовании времени Excel в время Unix является вычисление числового значения даты эпохи. Это можно сделать с помощью функции ДАТА.

Это дает нам эту ценность:

=25569

Таким же образом вычисленное числовое значение даты эпохи вычитается из числового значения данного времени в Excel.

=(40422-25569)
=(14853)

После этого рассчитанная выше разница умножается на 86400, чтобы получить результирующее значение в секундах.

=(14853)*86400

Это общее количество секунд, которое мы получаем между двумя датами.

=1283299200

Преобразование времени Unix в время Excel

И наоборот, мы можем преобразовать время Unix в время Excel с помощью следующей формулы:

1 = (B3 / 86400) + ДАТА (1970,1,1)

Пошаговое объяснение
Сначала временная метка Unix делится на общее количество секунд в дне, то есть 86400.

=14853

Теперь мы вычисляем числовое значение даты эпохи с помощью функции ДАТА.

=25569

Получив числовое значение даты эпохи, мы добавим эти два значения.

= 14853 + 25569
= 40422

Результирующее значение, которое мы получили после расчета, находится в формате порядкового номера даты. Чтобы просмотреть его в формате даты, просто измените формат ячейки на Дата или требуемый настраиваемый формат из числового формата, открыв его через вкладку «Главная».

или нажав CTRL + 1

После изменения формата числовых значений даты и времени Excel мы получаем следующие дату и время Excel

Преобразование времени Excel в время Unix в Google Таблицах

Формула преобразования времени в Unix-время в Google Таблицах работает точно так же, как и в Excel.

Вы поможете развитию сайта, поделившись страницей с друзьями

Here is a mapping for reference, assuming UTC for spreadsheet systems like Microsoft Excel:

                         Unix  Excel Mac    Excel    Human Date  Human Time
Excel Epoch       -2209075200      -1462        0    1900/01/00* 00:00:00 (local)
Excel ≤ 2011 Mac† -2082758400          0     1462    1904/12/31  00:00:00 (local)
Unix Epoch                  0      24107    25569    1970/01/01  00:00:00 UTC
Example Below      1234567890      38395.6  39857.6  2009/02/13  23:31:30 UTC
Signed Int Max     2147483648      51886    50424    2038/01/19  03:14:08 UTC

One Second                  1       0.0000115740…             —  00:00:01
One Hour                 3600       0.0416666666…             ―  01:00:00
One Day                 86400          1        1             ―  24:00:00

*  “Jan Zero, 1900” is 1899/12/31; see the Bug section below. Excel 2011 for Mac (and older) use the 1904 date system.

As I often use awk to process CSV and space-delimited content, I developed a way to convert UNIX epoch to timezone/DST-appropriate Excel date format:

echo 1234567890 |awk '{ 
  # tries GNU date, tries BSD date on failure
  cmd = sprintf("date -d@%d +%%z 2>/dev/null || date -jf %%s %d +%%z", $1, $1)
  cmd |getline tz                                # read in time-specific offset
  hours = substr(tz, 2, 2) + substr(tz, 4) / 60  # hours + minutes (hi, India)
  if (tz ~ /^-/) hours *= -1                     # offset direction (east/west)
  excel = $1/86400 + hours/24 + 25569            # as days, plus offset
  printf "%.9fn", excel
}'

I used echo for this example, but you can pipe a file where the first column (for the first cell in .csv format, call it as awk -F,) is a UNIX epoch. Alter $1 to represent your desired column/cell number or use a variable instead.

This makes a system call to date. If you will reliably have the GNU version, you can remove the 2>/dev/null || date … +%%z and the second , $1. Given how common GNU is, I wouldn’t recommend assuming BSD’s version.

The getline reads the time zone offset outputted by date +%z into tz, which is then translated into hours. The format will be like -0700 (PDT) or +0530 (IST), so the first substring extracted is 07 or 05, the second is 00 or 30 (then divided by 60 to be expressed in hours), and the third use of tz sees whether our offset is negative and alters hours if needed.

The formula given in all of the other answers on this page is used to set excel, with the addition of the daylight-savings-aware time zone adjustment as hours/24.

If you’re on an older version of Excel for Mac, you’ll need to use 24107 in place of 25569 (see the mapping above).

To convert any arbitrary non-epoch time to Excel-friendly times with GNU date:

echo "last thursday" |awk '{ 
  cmd = sprintf("date -d "%s" +"%%s %%z"", $0)
  cmd |getline
  hours = substr($2, 2, 2) + substr($2, 4) / 60
  if ($2 ~ /^-/) hours *= -1
  excel = $1/86400 + hours/24 + 25569
  printf "%.9fn", excel
}'

This is basically the same code, but the date -d no longer has an @ to represent unix epoch (given how capable the string parser is, I’m actually surprised the @ is mandatory; what other date format has 9-10 digits?) and it’s now asked for two outputs: the epoch and the time zone offset. You could therefore use e.g. @1234567890 as an input.

Bug

Lotus 1-2-3 (the original spreadsheet software) intentionally treated 1900 as a leap year despite the fact that it was not (this reduced the codebase at a time when every byte counted). Microsoft Excel retained this bug for compatibility, skipping day 60 (the fictitious 1900/02/29), retaining Lotus 1-2-3’s mapping of day 59 to 1900/02/28. LibreOffice instead assigned day 60 to 1900/02/28 and pushed all previous days back one.

Any date before 1900/03/01 could be as much as a day off:

Day        Excel   LibreOffice
-1            -1    1899/12/29
 0    1900/01/00*   1899/12/30
 1    1900/01/01    1899/12/31
 2    1900/01/02    1900/01/01
 …
59    1900/02/28    1900/02/27
60    1900/02/29(!) 1900/02/28
61    1900/03/01    1900/03/01

Excel doesn’t acknowledge negative dates and has a special definition of the Zeroth of January (1899/12/31) for day zero. Internally, Excel does indeed handle negative dates (they’re just numbers after all), but it displays them as numbers since it doesn’t know how to display them as dates (nor can it convert older dates into negative numbers). Feb 29 1900, a day that never happened, is recognized by Excel but not LibreOffice.

Return to Excel Formulas List

Download Example Workbook

Download the example workbook

This tutorial will demonstrate how to convert a time in Excel’s format to Unix time in Excel and Google Sheets.

mf convert time to unix times

What is Unix Time?

Unix time is also known as Epoch Time or POSIX time or Unix timestamp. It’s a system that counts the number of seconds that have elapsed since the Unix Epoch, i.e. January 1st, 1970. To put in simple words, Unix time is the total number of seconds between a date and Unix Epoch.

Convert Excel Time to Unix Time

To calculate Unix time, first, we need to find the total number of days between the Excel time and Epoch time. Then multiply the calculated days by 86,400, because a day has 86,400 seconds (24 hours × 60 minutes ×60 seconds = 86,400 seconds).

=(B5-DATE(1970,1,1))*86400

convert excel time to unix timestamp in excel

Step by Step Explanation

The first step in the conversion of Excel time to Unix time is to calculate the numeric value of the Epoch date. This can be done by using the DATE function.

=DATE(1970,1,1)

It gives us this value:

=25569

In the same way, the calculation of the numeric value of Epoch date is subtracted from the given Excel time’s numeric value

=(B5-DATE(1970,1,1))

=(40422-25569)
=(14853)

After that, the difference calculated from above is multiplied by 86400 to get the resultant value in seconds

=(14853)*86400

This is the total number of seconds, we get, between two dates

=1283299200

Convert Unix Time to Excel Time

Inversely, we can convert the Unix time to Excel time with the help of the following formula:

=(B3/86400)+DATE(1970,1,1)

unix timestamp to excel dateStep By Step Explanation

First, the Unix timestamp is divided by the total number of seconds in a day, i.e. 86400.

=B3/86400

=14853

Now, we calculate the numeric value of the Epoch date through DATE function

=DATE(1970,1,1)

=25569

Once we have the numeric value of the Epoch date, we’ll add these two values

= 14853 + 25569
= 40422

The resultant value, we got after the calculation, is in the serial date number format. To view it in date format, simply change the format of the cell to Date or your required custom format from the Number Format by accessing it through the Home Tab

date-format-hometab

or by pressing CTRL + 1

format cells

After changing the format of the numeric values of the Excel date & time, we get the following Excel date and time

convert unix time to excel date

Convert Excel Time to Unix Time in Google Sheets

The conversion formula for time to Unix time works exactly the same in Google Sheets as in Excel.

convert exceltime to unix timestamp in google sheets

Unix Timestamp conversions in Excel and in Power query are becoming more and more common.  With the ability to connect to a vast variety of data sources, the likelihood of you coming across a Unix timestamp is increasing.   The first time I came across a UNIX-based time was when I was connecting to a database from Excel and although the field was named Time, I had no idea what all these numbers meant, and I was left totally confused.

Unix time is commonly used in operating systems and programs that timestamp transactions as they happen.  The reason Unix time is used is that no matter where you live or the time zone you are in, this Unix timestamp represents a moment that is the same everywhere.

So, what is Unix time?  Unix time is the duration in seconds or milliseconds from midnight of the 1st January 1970 in UCT time.  It is represented by a 32-bit integer that can be positive or negative.  There is however a limitation of Unix time.  Unfortunately, there are upper and lower bounds which restricts the actual time span available.  Unix time spans from December 13th, 1901, and will end on the 19th of January 2038.  This is known as the Y38 Problem.

So now that you have a basic knowledge of Unix time, how can we work with this in Excel or Power Query?  Throughout the rest of this article, you are going to learn how to carry out Unix Timestamp conversions in Excel.  We will convert back and forth from Unix time to Excel time in both Excel and Power Query. 

How to convert Unix time to Excel Time

Let us first explore converting Unix time to Excel Time.  First, we will look at the formula when the timestamp is in second and then we will look at the formula when the timestamp is in milliseconds.

When time stamp in Seconds

The formula used to convert Unix timestamp recorded in seconds is:

= (Unix time/86400) +DATE (1970,1,1)

Remember to replace Unix Time with the cell reference that contains the Unix timestamp.

Once you enter this formula into the cell, the formula can be dragged down and copied to other cells in the workbook.

Unix Timestamp conversions in Excel

When the timestamp is in Milliseconds

The formula used to convert Unix timestamp recorded in milliseconds is:

= ((Unix time/1000)/86400) +DATE (1970,1,1)

Remember to replace Unix Time with the cell reference that contains the Unix timestamp.

Unix Timestamp conversions in Excel

How to convert Excel time to Unix time

With a reversal of the formula, we used to convert Unix time to Excel time, we can covert Excel time to Unix time.

The formula to convert Excel time to Unix time in seconds is.

= ((Excel Time – DATE(1970,1,1)) *86400

Remember to replace Excel Time in the formula with the cell reference that contains the time you wish to convert to Unix time.

Unix Timestamp conversions in Excel

The formula to convert Excel time to Unix time in milliseconds is.

= ((Excel Time -DATE (1970,1,1)) *1000) *86400

Unix Timestamp conversions in Excel

How to convert Unix time in Power query

Power query is used in both Excel and Power BI to connect to and transform data into a useable format.  The more you connect to different data sources the more often you will come across date columns in Unix format.  Once you have the data in Power query, a calculated column can be added to the data to carry out the conversions necessary.

How to convert from Unix time in Power Query for Excel and Power BI

From the Add Column tab on the ribbons in Power Query, select Custom Column.  This will allow us to set up a new column in our data based on a calculation or formula.

Unix Timestamp conversions in Excel

When we select Custom Column, a new box will open to allow us to enter a formula.  We can give our new column a name and enter the formula into the space provided.  Remember to replace [Unix time] with the column in Power query that contains the Unix time.

The formula we need to enter when converting from a timestamp recorded in seconds is as follows.

=#datetime(1970,1,1,0,0,0) + duration(0,0,0,[Unix time])

The formula we need to enter when converting from a timestamp recorded in milliseconds is as follows.

=#datetime(1970,1,1,0,0,0) + duration(0,0,0,[Unix time]/1000)

Unix Timestamp conversions in Excel

Once we confirm our formula by pressing OK, a new column will appear in Power query showing the date and time.

Unix Timestamp conversions in Excel

The last step is to ensure you set this new column to the correct data type.  This can be done from the Transform tab in the Power Query Ribbons. 

Unix Timestamp conversions in Excel

Depending on your need, you can select between

  • Date/Time
  • Date
  • Time
  • Date/Time/Time zone
  • Duration

In the example shown, we have selected the data type of Date.

Unix Timestamp conversions in Excel

How to convert to Unix time in Power Query for Excel and Power BI

Using Power Query in both Excel and Power BI it is easy to convert an Excel or Power BI date and time to a Unix timestamp using a custom column as we did above.

Once we have the date-time column in Power query, Select custom column.

Unix Timestamp conversions in Excel

The function we use to convert to Unix time is:

Duration.TotalSeconds([Excel date/time column]-#datetime(1970,1,1,0,0,0) )

(remember to replace [Excel date/time column] with the column that contains the date/time that you wish to convert to Unix.)

Unix Timestamp conversions in Excel

Conclusion

The more we work with different data sources in Excel Working with Unix Time in Excel and In Power Query for Excel and Power BI will become more and more common.  For this reason, we need to have the ability to convert Unix time to Excel time and Excel time to Unix time.  In this article, we looked at using both formulas and Power Query to carry out Unix Timestamp conversions in Excel.  If you are working with large sets of data, I would recommend the Power query option, but then if you are working with a large set of data that contains Unix timestamps, most likely you have used Power Query to connect to it in the first place.

Понравилась статья? Поделить с друзьями:
  • Перевод в восьмеричную систему счисления excel
  • Перевод в excel google
  • Перевод в excel 2007
  • Перевод аудиофайла в word
  • Перевод writings on the word