C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Convert string to dateIn today's time, it is a tedious task to analyze datasets with dates and times. Because of different lengths in months, distributions of the weekdays and weekends, leap years, and the time zones are the things that needs to consider according to our context. So, for this reason, Python has defined a new data type especially for dates and times called datetime. However, in many datasets, Strings are used to represent the dates. So, in this topic, you'll learn about converting date strings to the datetime format and see how these powerful set of tools helps to work effectively with complicated time series data. The challenge behind this scenario is how the date strings are expressed. For example, 'Wednesday, June 6, 2018' can also be shown as '6/6/18' and '06-06-2018'. All these formats define the same date, but the code represents to convert each of them is slightly different. fromdatetime import datetime # Define dates as the strings dmy_str1 = 'Wednesday, July 14, 2018' dmy_str2 = '14/7/17' dmy_str3 = '14-07-2017' # Define dates as the datetime objects dmy_dt1 = datetime.strptime(date_str1, '%A, %B %d, %Y') dmy_dt2 = datetime.strptime(date_str2, '%m/%d/%y') dmy_dt3 = datetime.strptime(date_str3, '%m-%d-%Y') #Print the converted dates print(dmy_dt1) print(dmy_dt2) print(dmy_dt3) Output: 2017-07-14 00:00:00 2017-07-14 00:00:00 2018-07-14 00:00:00 Converting the date string columnThis conversion shows how to convert whole column of date strings from the dataset to datetime format. From now on, you have to work with the DataFrame called eth that contains the historical data on ether, and also a cryptocurrency whose blockchain is produced by the Ethereum platform. The dataset consists the following columns:
Next TopicPandas Plot
|