6Dates
In the previous chapters we covered some of the main data types in Python but one thing that is quite important is dates. For anyone who has worked with dates they can be tricky things, there are different ways to format them and they can be hard to manipulate, however Python has you covered. If we want to create a datetime object we do so as follows (we earlier showed how to import the datetime package):
What we have done here is create a datetime by passing into dt the year, month, day, hour, minute, second to give us a datetime object. If we want to see it in a more friendly way we can type str around it and we get the string representation. Given we can define a date we can operate on dates as follows:
Here, we have created two dates and then subtracted one from the other. What we get back is a timedelta object and converting it to a string we can see that it represents the days and time from the date subtraction. To understand timedelta we can import it just as we did with datetime.
Now timedelta behaves a little different from datetime in that we do not pass in years and months but instead days, hours, minutes, and seconds. If you think about it setting a timedelta ...
Get The Python Book now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.