Python current timestamp in milliseconds

Python Datetime Examples

Unless otherwise noted Python version 3.6+ is used in all examples.

For examples on date arithmetic, see Python Date/Datetime Arithmetic Examples: Adding, Subtracting, etc

Build new Date object

All three arguments (year, month, day) are required.

from datetime import date # december 25th, 2018 d = date(2018, 12, 25) # datetime.date(2018, 12, 25) 

Get current date

from datetime import date d = date.today() d #datetime.date(2018, 11, 11) 

Date to ISO 8601 string

Call .isoformat() on the date object.

from datetime import date d = date(2002, 12, 4) print(d.isoformat()) # '2002-12-04' 

Date to string, custom format

Call .strftime() on the date object.

from datetime import date d = date(2002, 12, 4) print(d.strftime("%A, %b %d %Y")) # Wednesday, Dec 04 2002 

Date to string, no zero-padding

Use %-d to disable zero-padding:

from datetime import date d = date(2002, 12, 4) print(d.strftime("%A, %b %-d %Y")) # Wednesday, Dec 4 2002 

String to Date

Convert an ISO 8601 date string ( «YYYY-MM-DD» ) into a Date object.

Читайте также:  Инструмент для html css

Solution: Read it into a Datetime using strptime() then build a new Date object from that.

Example: read the string «2019-10-20» into a Date object

from datetime import date,datetime # read the string into a datetime object dt=datetime.strptime("2019-10-20", "%Y-%m-%d") # >>> datetime.datetime(2019, 10, 20, 0, 0) # then build a date object d = date(dt.year,dt.month,dt.day) # >>> datetime.date(2019, 10, 20) 

New Datetime object

from datetime import datetime # May 10, 2016 at 12:30:00 obj = datetime(2016,5,10,12,30,0,0) # datetime.datetime(2016, 5, 10, 12, 30) 

Current datetime

from datetime import datetime dt = datetime.now() dt # datetime.datetime(2018, 11, 11, 17, 56, 2, 701694) 

Datetime to ISO 8601 String

The ISO format for timestamps has a ‘T’ separating the date from the time part.

from datetime import datetime dt = datetime.now() dt.isoformat() # >>> '2020-02-25T01:19:18.900361' 

String to Datetime

Use datetime.strptime(date_string, format_string)

from datetime import datetime # 1st of December, 2016 date_str = "01-12-2016 12:34:56" format = "%d-%m-%Y %H:%M:%S" datetime_obj = datetime.strptime(date_str,format) datetime_obj # datetime.datetime(2016, 12, 1, 12, 34, 56) 

Datetime to string

from datetime import datetime obj = datetime(2016,5,10,12,30,0,0) print(obj.strftime('%d %b, %Y %H:%M:%S')) # '10 May, 2016 12:30:00' 

Datetime to Date

Use the default date constructor: date(year,month,day)

from datetime import date,datetime dt = datetime.now() # >>> 2019-10-20 15:53:19.085418 # get year, month and day form the datetime object d = date(dt.year,dt.month,dt.day) # >>> 2019-10-20 

ISO 8601 string to Datetime

On Python 3.7+, use datetime.fromisoformat() instead

Use strptime with this format: «%Y-%m-%dT%H:%M:%S.%f»

Example: read «2019-10-20T15:54:53.840416» into a datetime object

from datetime import datetime dt = datetime.now() iso_datetime_string = dt.isoformat() # >>> '2019-10-20T15:54:53.840416' datetime.strptime(iso_datetime_string,"%Y-%m-%dT%H:%M:%S.%f") # >>> datetime.datetime(2019, 10, 20, 15, 54, 53, 840416) 

Current timestamp in milliseconds

import time current_millis = int(round(time.time() * 1000)) current_millis # 1541966251776 

Get day of month from date object

from datetime import date today = date.today() # >>> datetime.date(2019, 4, 29) today.day # >>> 29 

Get day of week from date

Method Day numbers
isoweekday() Monday is 1, Sunday is 7
weekday() Monday is 0, Sunday is 6

Example date: 29 April, 2019 is a Monday.

from datetime import date d = date.today() # >>> datetime.date(2019, 4, 29) # with weekday(), 0 means monday d.weekday() # >>> 0 # with isoweekday(), 1 means monday d.isoweekday() # >>> 1 

Truncate date to start of week

This assumes the start of the week is Sunday.

Subtract the date by: timedelta(days = (dt.weekday() + 1) % 7)

from datetime import date, timedelta # April 7 2020 is a Tuesday dt = date(2020,4,7) # calculate the start of the week. dt_start_of_week = dt - timedelta(days = (dt.weekday() + 1) % 7) # April 5 2020 is the start of the Week (sunday) dt_start_of_week # >>> datetime.date(2020, 4, 5) 

References

Источник

How to get current time in milliseconds in Python?

In this article, we will discuss the various way to retrieve the current time in milliseconds in python.

Using time.time() method

The time module in python provides various methods and functions related to time. Here we use the time.time() method to get the current CPU time in seconds. The time is calculated since the epoch. It returns a floating-point number expressed in seconds. And then, this value is multiplied by 1000 and rounded off with the round() function.

NOTE : Epoch is the starting point of time and is platform-dependent. The epoch is January 1, 1970, 00:00:00 (UTC) on Windows and most Unix systems, and leap seconds are not included in the time in seconds since the epoch.

We use time.gmtime(0) to get the epoch on a given platform.

Syntax

The syntax of time() method is as follows −

Returns a float value that represents the seconds since the epoch.

Example

In the following example code, we use the time.time() method to get the current time in seconds. We then multiple by 1000 and we approximate the value by using the round() function.

import time obj = time.gmtime(0) epoch = time.asctime(obj) print("The epoch is:",epoch) curr_time = round(time.time()*1000) print("Milliseconds since epoch:",curr_time)

Output

The output of the above code is as follows;

The epoch is: Thu Jan 1 00:00:00 1970 Milliseconds since epoch: 1662372570512

Using the datetime module

Here we use various functions that are provided by the datetime module to find the current time in milliseconds.

Initially, we retrieve the current date by using the datetime.utc() method. Then we get the number of days since the epoch by subtracting the date 01-01-1670 (datetime(1970, 1, 1)) from the current date. For this date, we apply the .total_seconds() returns the total number of seconds since the epoch. Finally, we round off the value to milliseconds by applying the round() function.

Example

In the following example code, we get the current time in milliseconds by using different functions that are provided by the python datetime module.

from datetime import datetime print("Current date:",datetime.utcnow()) date= datetime.utcnow() - datetime(1970, 1, 1) print("Number of days since epoch:",date) seconds =(date.total_seconds()) milliseconds = round(seconds*1000) print("Milliseconds since epoch:",milliseconds)

Output

The output of the above example code is as follows;

Current date: 2022-09-05 10:10:17.745855 Number of days since epoch: 19240 days, 10:10:17.745867 Milliseconds since epoch: 1662372617746

Источник

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

Источник

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