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

Dates are always more difficult than you could ever imagine. Find out about the simplest case, naive dates, in this extract from Programmer's Python: Everything is Data.

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
  5. Sequences, Lists & Tuples
       Extract Sequences 
  6. Strings
       Extract Unicode Strings
  7. Regular Expressions
       Extract Simple Regular Expressions ***NEW!!!
  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>

Python doesn’t have a built-in native data type for working with dates and times and, arguably. it doesn’t need one. There is a standard module that will let you work with dates and times at a reasonably high-level abstraction. Even so. getting dates and times right is a minefield of unexpected problems and working out many of the relationships involving the calendar is tough. In this chapter we take a basic look at how Python represents and works with dates and times.

Naive and Aware Dates and Times

There are many complications about dates and times, but Python takes the simplest possible approach. The datetime object stores all of the information you need to specify a date and time. It is the date and time as shown on a calendar and clock – year, month, day, hour, minutes, seconds and microseconds. In this case there is no suggestion that the date and time applies to any particular location or any particular way of measuring time. This is referred to as a naive date and time and it is what you use if your program either always uses the same source of date and time or if you don’t care. For example, if you are creating a program that works on your desktop and all that matters is that dates and times relate to the date and time shown on your wall clock then you can simply record the values without worrying.

The reality of dates and time is that the way that they are measured differs depending on where you are in the world. Noon for me could be eight in the morning for you if you are in a different time zone. If you also store a time zone along with the date the data acquires an absolute interpretation – it is the time at a particular location and date including any adjustments for variations in time measurement such as daylight saving.

Notice that dates and times at a particular location can also be used as an absolute time. For example, UTC or Coordinated Universal Time is the successor to GMT (Greenwich Mean Time) and it is essentially the time on the line of zero longitude without any adjustment for daylight saving. The point is that UTC is the same for everyone no matter where they are located, but it only corresponds to local time in one time zone when there is no daylight saving.

Datetime Module

The datetime module provides three very similar classes:

date(year, month, day) 
time (hour, minute, second, microsecond)
datetime(year, month, day, hour, minute,
second, microsecond)

You can use date when you don’t need to record a time and time when you don’t need to record a date. In a date year has to be MINYEAR <= year <= MAXYEAR which is usually 1 <= year <= 9999. All date and time objects are immutable and hence hashable and so can be used as keys in a dictionary, see Chapter 8.

In each case you can leave out parameters and they default to zero. For simplicity the examples and discussion given below make use of datetime but you can substitute date or time and ignore the appropriate attributes and methods.

If you have a datetime object then you can obtain a time or a date object from it using;

  • date() return a date object with same date
  • time() return a time object with the same time and no timezone
  • timetz() return a time object with the same timezone.

You can also go the other way and combine a date and a time object to make a single datetime object:

combine(date, time, tzinfo = self.tzinfo)

The main purpose of the datetime object is to record the date and time of an event. Once created you can use it to display the date and time and to store it in a file.

As a datetime object is immutable, the replace method that allows you to generate a new object based on an existing object:

replace(year, month, day, hour, minute, second, microsecond)

creates a new datetime object but with any attributes specified modified.

Once you have a datetime object then you can access the individual components via attributes:

year

between MINYEAR and MAXYEAR inclusive

month

between 1 and 12 inclusive

day

between 1 and the number of days in the given month of the given year, taking account of leap years

hour

in range(24)

minute

in range(60)

second

in range(60)

Microsecond

in range(1000000)

You can get and set all of these integer attributes to test and modify the datetime object.

In addition you can use weekday() to return the day of the week, starting with Monday as 0, or use isoweekday for Monday as-1.

In many cases what you are interested in is finding a suitable string representation of the date and or time. The:

strftime(format)

method converts the datetime to a formatted string determined by the format parameter and the class method:

strptime(string,format)

converts a string to a datetime object using format to parse it. The format strings that you can use are fairly obvious and well documented, but you can still spend time searching for the format you actually want. Notice that many of the formats take account of the machine’s locale. For example, %A will give you the weekday name in the current language:

import datetime
dt = datetime.datetime(2022,1,14)
myString = dt.strftime("day name %A")
print(myString)

displays Friday in English locales.

If you want to use standard data and time ISO 8601 format the simplest approach is to use the:

isoformat(sep =string,timespec = items)

method. The format used is either:

YYYY-MM-DDTHH:MM:SS.ffffff, if microsecond is not 0

or

YYYY-MM-DDTHH:MM:SS, if microsecond is 0

The sep is a character to be used between the date and time and its default is T and timespec can be used to select which elements of the time are displayed. You can also convert an ISO date in a string to a datetime object using

fromisoformat(date_string)



Last Updated ( Wednesday, 02 October 2024 )