Python’s datetime library, part of its standard library, provides datatypes and methods for working with dates and times. Dates and times are slippery, irregular things, nevertheless, and libraries for working with them can just smooth things over so much.In this short article, we’ll check out how to utilize Python’s datetime library, its datatypes, and its techniques. You’ll learn how to take advantage of these features while staying away from their traps and complexities in Python.datetime items
and namespacing The name datetime refers to both the datetime library and to one of the Python datatypes. The library is namespaced as simply datetime. But the datatype for date-time items is namespaced as datetime.datetime.If you simply enter import datetime into a Python program, you’re just importing the datetime library. If you wish to work with the datetime datatype to create dates and times, then you need to refer to datetime.datetime or use from datetime import datetime. This will obtain the datatype item rather than the library.There are two methods to reduce confusion when dealing with the datetime library and datatype: Import things from the datetime library utilizing the from datetime import … syntax. The datetime datatype will only be
, you can instantiate it in among several ways: Use the current date and time with datetime.now(). For just the date, usage datetime.today(). Supply keyword arguments to the constructor, for year, month, and day, with extra choices
attempt to compare naive datetimes to datetimes with timezone details. If 2 datetimes have timezone info, it’s not tough to adjust them and determine their relationship. But if one is ignorant, there’s no way to compare them intelligibly.To that end, when you create datetime objects, get in the practice of adding a timezone. You can always use UTC time as a fallback, thus: For dt.datetime.now( ), you can pass in a timezone as an argument: dt.datetime.now(dt.timezone.utc). For dt.datetime, you can pass a timezone as the keyword argument tzinfo: dt.datetime(year=2023, month=4, day =1, tzinfo=dt.timezone.utc). If you have an existing ignorant datetime and you want to appoint
- a timezone to it, you can utilize the datetime.astimezone ()approach. This lets you pass in a timezone as an
- argument, and return a new datetime with a timezone included. The original datetime info is assumed to be UTC time.If you want to find
out what timezone (if any)is related to a datetime things, examine its.tzinfo home. None means you are taking a look at an ignorant datetime.Time distinctions and timedelta things datetime things describe a moment. If you desire an item that refers to a span of time, or the difference between 2 times, you need a different kind of things: a timedelta.timedelta objects are what you get when you take two datetime items and deduct one from the other to get the distinction. If you have a datetime from now and a datetime from an hour earlier, the resulting timedelta will represent that one-hour distinction. If you create a 3rd datetime value and add that timedelta to it, you’ll get a brand-new datetime object balanced out by that much time. Here’s a streamlined example: import time import datetime as dt now= dt.datetime.now( )time.sleep(10)# 10 seconds later on … now_2 =dt.datetime.now() ten_seconds_delta=now_2 -now now and now_2 were taken 10 seconds apart. Get the distinction between the two, and we have a timedelta things of 10 seconds.You can also create timedelta objects manually, by passing arguments to the constructor that describe the distinctions. Here’s an example utilizing a negative delta worth: import datetime as dt now =dt.datetime.now()minus_one_hour =dt.timedelta( hours =-1) one_hour_ago =now + minus_one_hour An important thing to understand about timedelta objects is that they may
appear to be missing out on certain units. They include time information (seconds, minutes, hours )and date details in the form of days. But they do not consist of weeks, months, or years.This isn’t a bug, however a deliberate omission. Date worths beyond counting days have inconsistent procedures, so there’s no pointin having them belong to
a timedelta. For instance, it does not make good sense to talk about a delta of”one month”if you do not know which months
are in question, since not all months have the exact same variety of days.(The same goes for years.)So if you want to discuss what took place on the same day of the last month, state the 30th, you need to make sure the last month had that day . Converting from and to POSIX timestamps A common format for time in computing is the POSIX timestamp, or the number of seconds(expressed as a float)since January 1, 1970. datetime things can be created from a timestamp with datetime.fromtimestamp(), which takes in the timestamp as an argument and an optional timezone. You can also yield a timestamp from a datetime item with datetime.timestamp (). Be warned that attempts to get a timestamp from a time item that’s outside the variety of legitimate times for a timestamp will raise an OverflowError exception. Simply put,
if you‘re processing historic dates, do not utilize POSIX timestamps to shop or serialize them. Utilize the ISO 8601 string format, described in the next section.Converting date and time strings If you wish to serialize a datetime challenge a string, the best and most portable method to do it is with datetime.isoformat (). This returns a string-formatted version of the datetime item in the ISO 8601 format; e.g.,’2023-04-11T12:03:17.328474’. This string can then be converted back into a datetime item with datetime.fromisoformat( ). For customized date/time formatting, datetime things provide datetime.strftime()to print a datetime item using custom-made formatting
, and datetime.strptime()to parse date/time strings with custom format. The format codes for strftime and strptime follow the