User Tools

Site Tools


convert_string_to_date

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
convert_string_to_date [2022/11/28 04:45] rajuconvert_string_to_date [2022/11/28 05:00] (current) raju
Line 1: Line 1:
-==== single date; without pandas; to datetime.date ====+===== Convert string to date ===== 
 +==== single date string; without pandas; to datetime.date ====
 Use <code> Use <code>
 from datetime import datetime from datetime import datetime
Line 26: Line 27:
 </code> </code>
  
-==== multiple dates; using pandas ====+Ref:- 
 +  * https://stackoverflow.com/questions/9504356/convert-string-into-date-type-on-python - where I found the answer 
 +  * https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes - shows the list of all the format codes such as %B, %Y. 
 + 
 +==== series of date strings; using pandas ====
 use <code> use <code>
 df[col_name] = pd.to_datetime(df[col_name], format_str) df[col_name] = pd.to_datetime(df[col_name], format_str)
Line 41: Line 46:
         'tag': ["3.11.0", "3.10.8", "3.10.7", "3.10.6", "3.10.5"]}         'tag': ["3.11.0", "3.10.8", "3.10.7", "3.10.6", "3.10.5"]}
 df = pd.DataFrame(data) df = pd.DataFrame(data)
-df['date'] = pd.to_datetime(df['date'], format='%Y-%m-%d') 
  
 In [2]: In [2]:
 +print(df)
 +         date     tag
 +0  2022-10-24  3.11.0
 +1  2022-10-08  3.10.8
 +2  2022-09-06  3.10.7
 +3  2022-08-08  3.10.6
 +4  2022-06-06  3.10.5
 +
 +In [3]:
 +print(df.dtypes)
 +date    object
 +tag     object
 +dtype: object
 +
 +In [4]:
 +df['date'] = pd.to_datetime(df['date'], format='%Y-%m-%d')
 +
 +In [5]:
 print(df) print(df)
         date     tag         date     tag
Line 52: Line 74:
 4 2022-06-06  3.10.5 4 2022-06-06  3.10.5
  
-In [3]:+In [6]:
 print(df.dtypes) print(df.dtypes)
 date    datetime64[ns] date    datetime64[ns]
Line 58: Line 80:
 dtype: object dtype: object
 </code> </code>
 +
 +See also: https://pandas.pydata.org/docs/reference/api/pandas.to_datetime.html
 +
convert_string_to_date.1669610711.txt.gz · Last modified: 2022/11/28 04:45 by raju