Python datetime format milliseconds

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

Источник

Convert DateTime to String With Milliseconds in Python

Convert DateTime to String With Milliseconds in Python

  1. Use the strftime() Method to Format DateTime to String
  2. Use the isoformat() Method to Format DateTime to String
  3. Use the str() Function to Format DateTime to String

The datetime module in Python allows us to create date and time objects easily manipulated and converted to different formats.

This tutorial will cover how to convert a datetime object to a string containing the milliseconds.

Use the strftime() Method to Format DateTime to String

The strftime() method returns a string based on a specific format specified as a string in the argument.

from datetime import datetime  date_s = (datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f'))  print(date_s) 

If we only import datetime , we would have to use datetime.datetime.now() to get the current date-time.

The %Y-%m-%d %H:%M:%S.%f is the string format. The now() method returns a datetime.datetime object of the current date and time. Notice that the final output has microseconds that could be easily truncated to milliseconds. For example:

from datetime import datetime  date_s = (datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3])  print(date_s) 

Use the isoformat() Method to Format DateTime to String

The isoformat() method of the datetime class returns a string representing the date in ISO 8601 format. We can specify the character which separates the date and time to be ‘ ‘ using the sep parameter and the timespace parameter that determines the time component to be milliseconds .

from datetime import datetime  date_s = datetime.now().isoformat(sep=' ', timespec='milliseconds')  print(date_s) 

Use the str() Function to Format DateTime to String

We can directly pass the datetime object to the str() function to get the string in the standard date and time format. This method is faster than the above methods, but we could specify the string format.

We can also simply remove the last three digits from the string to get the final result in milliseconds.

from datetime import datetime  t = datetime.now() date_s = str(t)[:-3]  print(date_s) 

Manav is a IT Professional who has a lot of experience as a core developer in many live projects. He is an avid learner who enjoys learning new things and sharing his findings whenever possible.

Related Article — Python DateTime

Источник

Читайте также:  Javascript change style all elements
Оцените статью