You probably already understand that in the computer memory, all numeric information is represented as ones and zeros, so at the most basic level, there isn't anything special about dates or times. However, when working with real data in business and technical projects, we tend to think about time or dates in their own units, differently from other numbers. Time is most often thought of as hours, minutes, or seconds, and dates are usually years, months, and days. Other common patterns are the weekdays, day of the week, business days, and quarters. We often group data into bins of days, weeks, months, or quarters. Within these bins, there might be data every second, minute, hour, or on some other or even random period. Because it is natural to think of dates and time of day together, Python in general, and pandas in particular, provides objects to make it easy to work this way. The most fundamental time component in pandas is Timestamp, and it is equivalent to Datetime in Python, provided by the datetime package. Timestamp is used as the index for pandas time series data types, as we'll see a bit later. pandas provides the Timestamp method to convert various types of data into timestamps. Here, we convert a string in a familiar date format into a pandas timestamp:
my_timestamp = pd.Timestamp('12-25-2020')
my_timestamp
This code snippet produces the following output:
It's intuitive that Timestamp consists of year, month, day, hour, minute, and second. Since we did not provide any time information, Timestamp() assumes that the time portion is 00:00:00. The fact that Timestamp has these components is what makes pandas times series operations so flexible. To illustrate that pandas is already simplifying things for us, here, we import Python datetime, and use it to accomplish the same conversion:
from datetime import datetime
my_datetime = datetime.strptime('12-25-2020','%m-%d-%Y')
my_datetime
This produces the following output:
You can see that, in the case of using the datetime method, we have to provide a date format for Python to decode the string. The two resulting objects have very similar methods available to them.
0 comments:
Post a Comment