Python Datetime Utcnow

In this article we are going to look at how we can see time in milliseconds, i.e. one thousandth (1000th) of a second, using Python. This could be for pure curiosity, benchmarking code or to get a very, very accurate time of day – whatever the reason, the focus of the article is how to get the time in milliseconds, rather than what it’s to be used for once we have it.

Method 1: Milliseconds and Fixed Time

Def stableutcnow: 'Returns a current datetime.utcnow that doesn't change during a request. You can use stableutcnow to make sure that timedeltas computed against utcnow in various areas of your code are consistent with each other without having to inject an explicit datetime into each one.

The first method we are going to look at is based on measuring how much time has passed since a fixed point in time, which we call the ‘epoch’. For Python, and computing in general, the epoch is the point where time starts and the passage of time is therefore measured against this. Whilst the epoch can vary depending on operating system, for Unix and Windows it is midnight on January 1st 1970 in UTC time (Greenwich Mean Time without Daylight Savings time adjustments). If you want to find out what the epoch time is on a given platform you can use:

  1. # Or getting the current time in UTC as a datetime object from utcnow import utcnow utcnow. Asdatetime # datetime.datetime(2021, 2, 18, 8, 24, 48, 382262, tzinfo=datetime.timezone.utc) # this is merely a convinience, as the same value would be returned by both: # 1. Utcnow.asdatetime # 2.
  2. Warning: datetime also provides datetime.utcnow , which returns an instance of datetime at the current UTC. However, the Python documentation recommends against using this method because it doesn’t include any time zone information in the resulting instance.
  3. In Python, the datetime module can be used to get date and time. This is good but there is something annoying: the milliseconds or the fraction that gets printed by default. How can we get rid of that? There are a couple of ways to do the trick. Let us see Example code. The following code snippet shows the default behavior.
  4. The following are 15 code examples for showing how to use datetime.timestamp.These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

As I am using a Windows 10 machine the above output just confirms that the start time, or the epoch for Python on my machine is January 1, 1970, 00:00:00.

Using time.time()

The time Python Standard Library can be used to return the time in seconds since the epoch as a floating point number:

This essentially gives us the number of seconds that have passed since the epoch, so to get the time in milliseconds we have to multiply the value returned by 1000. For aesthetics we can round the number and convert to an integer:

Whilst this is a good, basic way of getting time, if you are measuring time in milliseconds you are probably looking for a level of precision this does not provide. Unfortunately, the time.time is designed to get time in seconds, so can not guarantee that the system you are using will return a time with a precision greater than that i.e 1 second.

time.time_ns()

Appreciating this need for more accuracy, Python versions 3.7 and later incorporate an additional time function that measures time to the nanosecond – a thousand -millionth of a second. You may, like me, just need a moment to think about that – a thousand-millionth of a second…

So, whilst this method clearly has the precision we are looking for, to get the time in milliseconds we still need to divide the number returned by 1,000,000 (i.e convert nanoseconds to milliseconds):

As the function automatically returns an integer we do not need to worry about rounding or converting.

Method 2: Milliseconds and Relative Time

If our aim is to measure speed in milliseconds, for benchmarking code for example, Python has multiple functions in the time library that can specifically help with this. We are going to look at two, in particular, which can be used to measure time in nanoseconds so give us the precision we require.

Unlike the examples in Method 1, neither of these functions have a defined relationship to the real-world time – the epoch, they look at what we call relative time. The value they return is not defined against any starting point, but can be used to measure time intervals – such as how long it takes to run a task or specific piece of code. .

time.monotonic_ns()

This function is used to get the value of a monotonic clock, a clock that can not go backwards and is not affected by system clock updates. As the return value is undefined, i.e we don’t know what starting point it relates to, it has limited use on it’s own. However, we can sandwich some code between consecutive calls to measure the time between the calls and therefore how long it took to execute our code.

Python Datetime Utcnow

In the example below, we will print the start monotonic time and the finish monotonic time for illustration purposes as they have no value on their own. We can however use them to measure the time between the two calls to see how long it took for Python to perform the print function. As the return value is in nanoseconds, we have to divide by 1,000,000 to get our millisecond response time

The output is:

time.perf_counter_ns()

This method is similar to the time.monotonic function previously outlined but, as the name suggests, is a performance counter. It does not include time elapsed during sleep and is system-wide. This returns the absolute value of the counter but as this return is undefined, as with the time.monotonic function, it has limited use on it’s own.

So, as with the time.monotonic function we can use consecutive calls to measure time between the calls, and as the return is in nanoseconds we have to divide by 1,000,000 to get milliseconds:

The output is:

With both the time.perf_counter and time.monotonic functions, the start and finish times we have printed are irrelevant on their own, because we do not know what they relate to. Their only use is to show us the time elapsed between the calls.

Method 3: Milliseconds and Time of Day

Finally, we are going to look at how we can get Python to tell us the time of day in milliseconds, and to do this we will be using the Python Standard Library datetime.

datetime.datetime.now()

This function returns the current system date and time with the following attributes:

year, month, day, hour, minute, second, microsecond

If we just call the function by itself it will show us the current date and time at my location, down to the microsecond (one millionth of a second) :

The above output tells me current local time is

  • Year: 2021
  • Month: 2 (February)
  • Day: 18
  • Hour: 12
  • Minutes: 21
  • Seconds: 7
  • Microseconds: 163392

The thing to bear is that the micorsecond attribute being returned is always in relation to the seconds attribute.

Now if we want to convert the microseconds to milliseconds we have to divide by 1000, we can also use a print statement to help format the function for readability:

The output is:

The first line of the output prints the current date and time, the second line prints the number of milliseconds at this point.

datetime.datetime.utcnow()

A slight variation on the previous example is using utcnow() instead of just now(). UTC refers to time in Coordinated Universal Time or Greenwich Mean Time(GMT) and is useful to calculate absolute time differences without the confusion of time zones. As I live in London, there is no difference in my code between now() and utcnow() but we will see it in action anyway.

If we call the function without any formatting we get a similar output to what we saw before, so the attributes are the same :

We could get our milliseconds as we did with the now() function, and it would work just as well, but let’s have a look at another method. In this example we are going to use the strftime() method to convert our datetime object into a string:

As the last number represents microseconds if we want to display the current time in milliseconds we can disregard the last 3 digits, by slicing. This has the same effect as dividing by 1000 thus converting or time to microseconds:

Summary

Datetime

We have looked at several ways of using Python to show us time in milliseconds. Whilst the update from the simple time.time to time.time_ns definitely helps with our precision, it is difficult to provide recommendations on best practice. All the methods we have seen provide an answer, but whether it’s the right answer really depends on the question we are asking.

The key is finding the right method to fit your particular requirements, factors like level of precision required, geographical location(s) and level of complexity will all determine the right approach. Luckily Python has a number of ways to help us get milliseconds, so it could come down to personal preference.

Related Posts

Purpose:The datetime module includes functions and classes for doingdate and time parsing, formatting, and arithmetic.

datetime contains functions and classes for working with datesand times, separately and together.

Python

Times¶

Time values are represented with the time class. Atime instance has attributes for hour,minute, second, and microsecond and can alsoinclude time zone information.

The arguments to initialize a time instance are optional, butthe default of 0 is unlikely to be correct.

A time instance only holds values of time, and not a dateassociated with the time.

The min and max class attributes reflect the validrange of times in a single day.

The resolution for time is limited to whole microseconds.

Floating point values for microseconds cause a TypeError.

Dates¶

Calendar date values are represented with the dateclass. Instances have attributes for year, month, andday. It is easy to create a date representing the current dateusing the today() class method.

This example prints the current date in several formats:

There are also class methods for creating instances from POSIXtimestamps or integers representing date values from the Gregoriancalendar, where January 1 of the year 1 is 1 and each subsequentday increments the value by 1.

This example illustrates the different value types used byfromordinal() and fromtimestamp().

As with time, the range of date values supported can bedetermined using the min and max attributes.

The resolution for dates is whole days.

Another way to create new date instances uses thereplace() method of an existing date.

This example changes the year, leaving the day and month unmodified.

timedeltas¶

Future and past dates can be calculated using basic arithmetic on twodatetime objects, or by combining a datetime with atimedelta. Subtracting dates produces a timedelta,and a timedelta can be added or subtracted from a date toproduce another date. The internal values for a timedelta arestored in days, seconds, and microseconds.

Intermediate level values passed to the constructor are converted intodays, seconds, and microseconds.

The full duration of a timedelta can be retrieved as a numberof seconds using total_seconds().

The return value is a floating point number, to accommodate sub-seconddurations.

Date Arithmetic¶

Date math uses the standard arithmetic operators.

This example with date objects illustrates using timedeltaobjects to compute new dates, and subtracting date instances toproduce timedeltas (including a negative delta value).

A timedelta object also supports arithmetic with integers,floats, and other timedelta instances.

Datetime

In this example, several multiples of a single day are computed, withthe resulting timedelta holding the appropriate number ofdays or hours. The final example demonstrates how to compute values bycombining two timedelta objects. In this case, the result isa floating point number.

Comparing Values¶

Both date and time values can be compared using the standardcomparison operators to determine which is earlier or later.

All comparison operators are supported.

Combining Dates and Times¶

Use the datetime class to hold values consisting of both dateand time components. As with date, there are severalconvenient class methods to make creating datetime instancesfrom other common values.

As might be expected, the datetime instance has all of theattributes of both a date and a time object.

Just as with date, datetime provides convenientclass methods for creating new instances. It also includesfromordinal() and fromtimestamp().

combine() creates datetime instances from onedate and one time instance.

Formatting and Parsing¶

The default string representation of a datetime object uses theISO-8601 format (YYYY-MM-DDTHH:MM:SS.mmmmmm). Alternate formatscan be generated using strftime().

Use datetime.strptime() to convert formatted strings todatetime instances.

The same formatting codes can be used with Python’s string formattingmini-language by placing them after the : in the fieldspecification of the format string.

Each datetime format code must still be prefixed with %, andsubsequent colons are treated as literal characters to include in theoutput.

The following table demonstrates all of the formatting codes for 5:00PM January 13, 2016 in the US/Eastern time zone.

strptime/strftime format codes
SymbolMeaningExample
%aAbbreviated weekday name'Wed'
%AFull weekday name'Wednesday'
%wWeekday number – 0 (Sunday) through 6 (Saturday)'3'
%dDay of the month (zero padded)'13'
%bAbbreviated month name'Jan'
%BFull month name'January'
%mMonth of the year'01'
%yYear without century'16'
%YYear with century'2016'
%HHour from 24-hour clock'17'
%IHour from 12-hour clock'05'
%pAM/PM'PM'
%MMinutes'00'
%SSeconds'00'
%fMicroseconds'000000'
%zUTC offset for time zone-aware objects'-0500'
%ZTime Zone name'EST'
%jDay of the year'013'
%WWeek of the year'02'
%cDate and time representation for the current locale'WedJan1317:00:002016'
%xDate representation for the current locale'01/13/16'
%XTime representation for the current locale'17:00:00'
%%A literal % character'%'

Time Zones¶

Within datetime, time zones are represented by subclasses oftzinfo. Since tzinfo is an abstract base class,applications need to define a subclass and provide appropriateimplementations for a few methods to make it useful.

datetime does include a somewhat naive implementation in theclass timezone that uses a fixed offset from UTC, and doesnot support different offset values on different days of the year,such as where daylight savings time applies, or where the offset fromUTC has changed over time.

Python Datetime To Utc

To convert a datetime value from one time zone to another, useastimezone(). In the example above, two separate time zones 6hours on either side of UTC are shown, and the utc instance fromdatetime.timezone is also used for reference. The final outputline shows the value in the system timezone, acquired by callingastimezone() with no argument.

Note

Python Datetime Utcnow Format

The third party module pytz is a better implementation for timezones. It supports named time zones, and the offset database iskept up to date as changes are made by political bodies around theworld.

See also

Python Datetime Format

  • calendar – The calendar module.
  • time – The time module.
  • dateutil – dateutilfrom Labix extends the datetime module with additionalfeatures.
  • pytz – World Time Zone database and classes for makingdatetime objects time zone-aware.
  • WikiPedia: Proleptic Gregorian calendar –A description of the Gregorian calendar system.
  • ISO 8601 – The standard for numeric representation of Datesand Time