Python time format milliseconds

Python display milliseconds in formatted string using `time.strftime`

I am trying to format milliseconds to formatted string preserving the milliseconds part. Here’s my code:

import time time.strftime('%Y-%m-%d %H:%M:%S:%f', time.gmtime(1515694048121/1000.0)) 

where 1515694048121 is a time in milliseconds. It returns me:

As we can see, the millisecond portion of time is not returned.

What is correct format to include millisecond portion of time? Is ‘%Y-%m-%d %H:%M:%S:%f’ not correct ?

There is the no directive mentioned in time.strftime(. ) that will return you the milliseconds. Not sure from where you got the reference to use %f . In fact time.gmtime(. ) holds the precision only upto seconds.

As a hack, in order to achieve this, you may explicitly format your string by preserving your milli second value as:

>>> import time >>> time_in_ms = 1515694048121 >>> time.strftime('%Y-%m-%d %H:%M:%S:<>'.format(time_in_ms%1000), time.gmtime(time_in_ms/1000.0)) '2018-01-11 18:07:28:121' 

Here’s the list of valid directives:

+-----------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------+ | Directive | Meaning | Notes | +-----------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------+ | %a | Locale’s abbreviated weekday name. | | | %A | Locale’s full weekday name. | | | %b | Locale’s abbreviated month name. | | | %B | Locale’s full month name. | | | %c | Locale’s appropriate date and time representation. | | | %d | Day of the month as a decimal number [01,31]. | | | %H | Hour (24-hour clock) as a decimal number [00,23]. | | | %I | Hour (12-hour clock) as a decimal number [01,12]. | | | %j | Day of the year as a decimal number [001,366]. | | | %m | Month as a decimal number [01,12]. | | | %M | Minute as a decimal number [00,59]. | | | %p | Locale’s equivalent of either AM or PM. | (1) | | %S | Second as a decimal number [00,61]. | (2) | | %U | Week number of the year (Sunday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Sunday are considered to be in week 0. | (3) | | %w | Weekday as a decimal number [0(Sunday),6]. | | | %W | Week number of the year (Monday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Monday are considered to be in week 0. | (3) | | %x | Locale’s appropriate date representation. | | | %X | Locale’s appropriate time representation. | | | %y | Year without century as a decimal number [00,99]. | | | %Y | Year with century as a decimal number. | | | %z | Time zone offset indicating a positive or negative time difference from UTC/GMT of the form +HHMM or -HHMM, where H represents decimal hour digits and M represents decimal minute digits [-23:59, +23:59]. | | | %Z | Time zone name (no characters if no time zone exists). | | | %% | | | +-----------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------+ 

Источник

Читайте также:  Импорт класса в php

Get Current Time in Python (Different Formats & Timezones)

For example, here is a simple piece of code to get the current time:

from datetime import datetime now = datetime.now().strftime("%H:%M:%S") print(f"The time is ")

This displays the current time in HH:MM:SS format:

This is a comprehensive guide to getting the current time in Python.

You will learn how to get the current time in different formats and contexts in Python. For example, you’ll learn how to get the current time in milliseconds, in the Epoch format, and how to extract different time components from it.

Current Time in Python

Dealing with time is crucial in some Python programs. To make handling instances of time easier in your projects, Python has some useful libraries like time and datetime.

Read more about using the datetime module in Python.

Let’s take a complete look at how you can get the current time in Python using different timezones, formats, and such.

Current Time in Milliseconds

Current time in milliseconds in Python

Milliseconds means one-thousandth (1/1000th) of a second.

To get the current time in milliseconds in Python:

import time t = time.time() t_ms = int(t * 1000) print(f"The current time in milliseconds: ")
The current time in milliseconds: 1635249073607

Current Time in Seconds

Python code of current time in seconds

To get the current time in seconds in Python:

import time t = time.time() t_s = int(t) print(f"The current time in seconds: ")
The current time in seconds: 1635249118

Get Current Local Date and Time

Local date and time in Python

To get the current local date and time in Python:

  1. Import the datetime class from the datetime module.
  2. Ask for the current time by datetime.now().
from datetime import datetime now = datetime.now() print(f"The timestamp is ")
The timestamp is 2021-10-26 14:53:37.807390

Get Current Timezone

Python code to get the current timezone info

To get the current local timezone in Python:

  1. Import the datetime class from the datetime module.
  2. Get the current time.
  3. Convert the current time to time that stores timezone information.
  4. Get your local timezone from the timezone information.
from datetime import datetime now = datetime.now() now_with_tz = now.astimezone() my_timezone = now_with_tz.tzinfo print(my_timezone)

I am in the EEST timezone (Eastern European Summer Time), so the above code gives me:

Get Current Epoch/Unix Timestamp

Epcoh time in Python

The epoch time/UNIX time refers to how many seconds have passed since Jan 1st, 1970.

To get the current epoch/UNIX timestamp in Python:

import time t_epoch = time.time() print(f"The epoch time is now: ")
The epoch time is now: 1635251715.9572039

Current UTC Time

Code to get the current UTC time in Python

To get the current time in UTC time format in Python:

from datetime import datetime, timezone now = datetime.now(timezone.utc) print(f"Current UTC Time: ")
Current UTC Time: 2021-10-26 12:01:54.888681+00:00

Current ISO Time

The Python code to get the current time in ISO format

The ISO 8601 (International Organization for Standardization) is a standard way to express time.

ISO 8601 follows the format T[hh]:[mm]:[ss].

To get the current time in ISO format in Python:

  1. Import the datetime class from the datetime module.
  2. Convert current time to ISO format.
from datetime import datetime ISO_time = datetime.now().isoformat() print(f"Current DateTime in ISO: ")
Current DateTime in ISO: 2021-10-26T15:02:36.635934

Current GMT Time

A piece of code to get the current GMT time

The GMT or Greenwich Mean Time is the solar time observed in Greenwich, London.

To get the current GMT time in Python:

  1. Import gmttime, strftime from the time module.
  2. Get the GMT time with the gmttime() function.
  3. Format the time.
from time import gmtime, strftime now_GMT = strftime("%a, %d %b %Y %I:%M:%S %p %Z", gmtime()) print("GMT time is now: " + now_GMT)
GMT time is now: Tue, 26 Oct 2021 12:10:09 PM UTC

Get Current Years, Months, Days, Hours, Minutes, and Seconds

Extracting years, months, days, hours, minutes, and seconds from time

To extract years, months, days, hours, minutes, and seconds in Python:

  1. Import the datetime class from the datetime module.
  2. Get the current date object.
  3. Pull the time components from the current date object.
from datetime import datetime now = datetime.now() print(f"Year: ") print(f"Month: ") print(f"Day: ") print(f"Hour: ") print(f"Minute: ") print(f"Second: ")
Year: 2021 Month: 10 Day: 26 Hour: 15 Minute: 13 Second: 48

This completes the guide! I hope you find it useful and learned something new. Thanks for reading. Happy coding!

Further Reading

Источник

Форматирование даты и времени в Python

Форматирование даты и времени в Python

Сегодня рассмотрим два метода strftime и strptime из стандартной библиотеки datetime в языке программирования Python.

Описание формата strftime

Кратко говоря, strftime преобразует объект date в строковую дату.

Это выглядит так: dateobject.strftime(format).

«Format» — это желаемый формат строки даты, который хочет получить пользователь. Формат строится с использованием кодов, приведенных ниже:

  • %a — будний день сокращенно (Пн, Вт,…)
  • %A — будний день полностью (Понедельник, Вторник,…)
  • %w — будний день, как десятичное число (1, 2, 3,…)
  • %d — день месяца в числах (01, 02, 03,…)
  • %b — месяцы сокращенно (Янв, Фев,…)
  • %B — название месяцев полностью (Январь, Февраль,…)
  • %m — месяцы в числах (01, 02, 03,…)
  • %y — года без века (19, 20, 21)
  • %Y — года с веком (2019, 2020, 2021)
  • %H — 24 часа в сутки (с 00 до 23)
  • %I — 12 часов в сутки (с 01 до 12)
  • %p — AM и PM (00-12 и 12-00)
  • %M — минуты (от 00 до 59)
  • %S — секунды (от 00 до 59)
  • %f — миллисекунды (6 десятичных чисел)

Использование strftime

Давайте рассмотрим конкретный пример — преобразование текущего времени в строку даты:

import datetime from datetime import datetime now = datetime.now() print(now)

Давайте теперь преобразуем приведенный выше объект datetime в строку datetime:

Если вы хотите напечатать месяц в качестве сокращенного названия, замените %m на %b, как показано ниже:

Преобразование даты в strftime

Преобразование даты в строку очень похоже на преобразование datetime в строку.

Рассмотрим пример — преобразование текущего объекта даты в строку даты:

today = datetime.today() print(today)

Давайте преобразуем приведенный выше объект date в строку даты с помощью метода strftime:

Отображение миллисекунд

Чтобы получить строку даты с миллисекундами, используйте код формата %f в конце, как показано ниже:

today = datetime.today() today.strftime("%Y-%m-%d %H:%M:%S.%f")

Описание формата strptime

Strptime используется для преобразования строки в объект datetime. Тоесть обратное действие методу strftime. Это выглядит так: strptime(date_string, format).

Разберем пример: strptime(«9/23/20», «%d/%m/%y»). Формат «%d/%m/%y» представляет собой соответствующий формат «9/23/20». Результатом приведенной выше команды будет объект datetime.

Формат строится с использованием заранее определенных кодов. Есть много кодов на выбор. Наиболее важные из них были перечислены ранее (смотрите 1 пункт в содержании).

Использование метода strptime

Преобразуем строку даты в объект datetime:

import datetime datetime.datetime.strptime("09/23/2030 8:28","%m/%d/%Y %H:%M")
datetime.datetime(2030, 9, 23, 8, 28)

Заключение

На этом всё. Желаю удачи в программировании!

Программирую на Python с 2017 года. Люблю создавать контент, который помогает людям понять сложные вещи. Не представляю жизнь без непрерывного цикла обучения, спорта и чувства юмора.

Ссылка на мой github есть в шапке. Залетай.

Егоров Егор

Здравствуйте, Егор!
Статья замечательная, спасибо за неё!
Пытаюсь научиться программировать, невзирая на свой зрелый возраст.
Предполагаю, что метод «strptime» должен понадобиться мне для решения ближайших намеченных задач преобразования частей строк вида «31 декабря 2010» в объекты datetime — («%d/%m/%Y»).
Наверное «декабря» и прочие неправильные или лишние буквы в названиях месяцев, тоже придётся обрабатывать до вида «декабрь»? Будет видно по мере реализации задачи.
С преобразованием времени (часы, минуты) вроде должно быть проще.
Надеюсь в Python 3.8 всё это будет работать.

Здравствуйте, Борис.
Я бы советовал вам, произвести небольшое сопоставление строчного именования месяца в численное.
Например: «Январь», «Января» — 01,
«Февраль», «Февраля» — 02,
«Март», «Марта» — 03. Для того, чтобы легче было преобразовать дату в формат datetime.

Источник

Оцените статью