Programmer's Python Data - Naive Dates
Written by Mike James   
Wednesday, 02 October 2024
Article Index
Programmer's Python Data - Naive Dates
Timestamps

Timestamps

You can use the datetime object to record and work with dates and times in a human-oriented representation. This is far too wasteful a format for recording dates and times as part of the operating system. For example, every file has a creation date and time stored along with it and this needs to be compact to avoid wasting storage. These data and time records are generally called timestamps and we need to know how they work and how to convert them to a datetime object.

The key idea in using a timestamp is that they generally record the date and time from some fixed point and usually as the number of seconds or milliseconds that have elapsed. Most operating systems follow Unix in recording the number of seconds from:

Thursday Jan 1st 00:00:00 UTC 1970.

Why this exact date in 1970? The reason is that this is the Unix epoch, i.e it is around the time when the Unix operating system was created. Keeping time in seconds from this date is usually called "Unix time", Epoch time or Posix time. At the moment Unix time is generally recorded using a 32-bit integer which means it will roll over in 2038, creating the so-called “year 2038 problem”. Upgrades to 64-bit integer representation is in progress and this won’t roll over until 292 billion years have elapsed. Also notice that Unix time is both positive and negative with negative second counts being taken to represent time before the epoch. It is also customary to supplement the Unix time by an additional 32-bit integer that records milliseconds or nanoseconds. In practice, the accuracy of timestamps is very much lower than this. It is also worth noting that Unix time is a rough approximation to UTC as it handles leap seconds differently. Most of the time you can ignore the differences unless accuracy to the second is essential.

So how do you access a timestamp? The most direct way is to use the:

fromTimestamp(timestamp)

method which constructs a datetime object from the timestamp. Unless you specify a time zone as a second parameter, the local time of the system is used. If you need a UTC datetime object from the timestamp you can either specify the time zone explicitly or use:

utcfromTimestamp(timestamp)  

Of course, you need an actual timestamp to convert to a datetime object and these can be read from data files or from the metadata associated with file or many other sources. The most direct way is to simply present an integer value of seconds since the epoch. For example:

dt = datetime.datetime.fromtimestamp(0)
myString = dt.isoformat()
print(myString)

displays:

1970-01-01T00:00:00

which is, of course, the start of the epoch.

If you are converting timestamps derived from external sources you need to keep in mind that the value may be in milliseconds rather than seconds and you need to scale it. You can specify fractional seconds as part of a Python timestamp.

You can also derive a timestamp from a datetime object using the

timestamp()

method which returns a timestamp corresponding to the current date and time. This method makes use of a system function call which converts the date and time from local time to UTC and then to a timestamp, see Chapter 16. The system function doesn’t support the same range of dates and times that the datetime object does and hence it is possible to trigger an exception for dates in the distant past and far future. You can also obtain a timestamp using the time method of the time object in the time module, see later.

Today and Now

Often you need the current time and date and there are some very simple methods that will read the system’s hardware and return the current time and date. The today() method returns the current date and time using the local timezone and it also sets the datetime object’s timezone.
The now(tz = timezone)method does the same job, but allows you to set the timezone. If you don’t specify a time zone, this works exactly like today().

If you want nothing to do with time zones you can create a naive datetime object using:

utcnow()

which returns the UTC date and time. Notice that if you use this method the datetime object runs the risk of being treated as being in local time by other methods.

In Chapter but not in this extract

  • Time Zones and Aware Datetime Objects
  • Converting Times
  • Date and Time Arithmetic
  • Calendar Calculations

Summary

  • Dates and times don’t need a special fundamental data type because they are representable using basic integers.

  • The biggest problem in working with times is to take account of time zones. You can choose to ignore the problem and work with naive dates and times or record the time zone and take account of it with aware dates and times.

  • The datetime object creates human readable dates and times which are too inefficient for machine use.

  • The Unix timestamp which is just an integer count of seconds from a fixed date. Thursday Jan 1st 00:00:00 UTC 1970 is the most commonly encountered.

  • Unix timestamps are not standard in their representation. Some use ints, some use floats, some use ints augmented by an additional count of milliseconds.

  • You can get the current date and time using Today or Now if you need to record the time zone.

  • Time zones are complicated and if you opt to use aware dates and times you should also use the zoneinfo module and the IANA time zone database.

  • Converting between time zones can be tricky – use astimezone to convert times to their equivalents in other time zones.

  • Date and time arithmetic only needs date and time intervals which are recorded in timedelta objects.

  • You can do all reasonable date and time arithmetic with dates and times and timedelta objects.

  • Calendar calculations are tricky and interesting in the sense that there are often simple calculations that give you the answer to questions that look as if they need a program.

 

Programmer's Python
Everything is Data

Is now available as a print book: Amazon

pythondata360Contents

  1. Python – A Lightning Tour
  2. The Basic Data Type – Numbers
       Extract: Bignum
  3. Truthy & Falsey
  4. Dates & Times
       Extract Naive Dates ***NEW!!!
  5. Sequences, Lists & Tuples
       Extract Sequences 
  6. Strings
       Extract Unicode Strings
  7. Regular Expressions
  8. The Dictionary
       Extract The Dictionary 
  9. Iterables, Sets & Generators
       Extract  Iterables 
  10. Comprehensions
       Extract  Comprehensions 
  11. Data Structures & Collections
       Extract Stacks, Queues and Deques
      
    Extract Named Tuples and Counters
  12. Bits & Bit Manipulation
       Extract Bits and BigNum 
  13. Bytes
       Extract Bytes And Strings
       Extract Byte Manipulation 
  14. Binary Files
  15. Text Files
  16. Creating Custom Data Classes
        Extract A Custom Data Class 
  17. Python and Native Code
        Extract   Native Code
    Appendix I Python in Visual Studio Code
    Appendix II C Programming Using Visual Studio Code

<ASIN:1871962765>

<ASIN:1871962749>

<ASIN:1871962595>

<ASIN:B0CK71TQ17>

<ASIN:187196265X>

Related Articles

Creating The Python UI With Tkinter

Creating The Python UI With Tkinter - The Canvas Widget

The Python Dictionary

Arrays in Python

Advanced Python Arrays - Introducing NumPy

kotlin book

 

Comments




or email your comment to: comments@i-programmer.info

To be informed about new articles on I Programmer, sign up for our weekly newsletter, subscribe to the RSS feed and follow us on Twitter, Facebook or Linkedin.

Banner



Last Updated ( Wednesday, 02 October 2024 )