User Tools

Site Tools


manipulating_dates_in_python

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
manipulating_dates_in_python [2022/11/27 18:04] – [Tasks] rajumanipulating_dates_in_python [2024/02/06 05:22] (current) raju
Line 1: Line 1:
 ===== Tasks ===== ===== Tasks =====
-  * [[add dates]] +  * [[Add dates]] 
-    * tags | strptime+    * uses | strptime 
 +  * [[Convert string to date]]
  
 ===== Dummy ===== ===== Dummy =====
  
-==== Convert string to date ==== +==== date in isoformat ==== 
-Use <code>+ 
 +<code> 
 +from datetime import date 
 +today = date.today().isoformat() 
 +print(type(today)) 
 +print(today) 
 + 
 +<class 'str'> 
 +2023-09-18 
 +</code> 
 + 
 +It also works on datetime objects and will give the time in ISO 8601 format. 
 +<code>
 from datetime import datetime from datetime import datetime
-datetime.strptime(date_str, date_fmt).date()+now = datetime.today().isoformat() 
 +print(type(now)) 
 +print(now) 
 + 
 +<class 'str'> 
 +2023-09-18T13:55:17.214513
 </code> </code>
-Example:+ 
 +Ref:- https://stackoverflow.com/questions/32490629/getting-todays-date-in-yyyy-mm-dd-in-python 
 + 
 +==== extract date from datetime ====
 <code> <code>
 $ ipython $ ipython
Line 20: Line 41:
 from datetime import datetime from datetime import datetime
 s = '24 October 2022' s = '24 October 2022'
-dt = datetime.strptime(s, '%d %B %Y').date()+dtt = datetime.strptime(s, "%d %B %Y") 
 +print(dtt) 
 +2022-10-24 00:00:00
  
 In [2]: In [2]:
 +type(dtt)
 +Out[2]:
 +datetime.datetime
 +
 +In [3]:
 +dt = datetime.strptime(s, "%d %B %Y").date()
 print(dt) print(dt)
 2022-10-24 2022-10-24
  
-In [3]:+In [4]:
 type(dt) type(dt)
-Out[3]:+Out[4]:
 datetime.date datetime.date
 </code> </code>
 +
 ==== get today's day, month and year ==== ==== get today's day, month and year ====
 <code> <code>
Line 129: Line 159:
   * http://pandas.pydata.org/pandas-docs/stable/generated/pandas.date_range.html   * http://pandas.pydata.org/pandas-docs/stable/generated/pandas.date_range.html
  
 +==== print the names of months in a year ====
 +<code>
 +$ ipython
 +Python 3.11.4 | packaged by Anaconda, Inc. | (main, Jul  5 2023, 13:47:18) [MSC v.1916 64 bit (AMD64)]
 +IPython 8.12.0 -- An enhanced Interactive Python. Type '?' for help.
 +
 +In [1]:
 +import calendar
 +for m in calendar.month_name:
 +    print(m)
 +
 +
 +January
 +February
 +March
 +April
 +May
 +June
 +July
 +August
 +September
 +October
 +November
 +December
 +</code>
  
manipulating_dates_in_python.1669572242.txt.gz · Last modified: 2022/11/27 18:04 by raju