Playing with dates in python
In this tutorial you will be able to.
- Get current date/time
- Get weeks first and last date based on current date/time
- Get months first and last date based on current date/time
First we will find current date time
Step 1: Import necessary libraries (for above all task this is necessary step)
Step 1: Import necessary libraries (for above all task this is necessary step)
from datetime import datetime, timedelta
from calendar import monthrange
from calendar import monthrange
Step 2: Get current date/time and just print it
today = datetime.now()
print(today)
print(today)
Now we will find weeks first and last date based on current date/time
start = datetime.now() - timedelta(days=datetime.now().weekday())
end = start + timedelta(days=6)
print(start)
print(end)
end = start + timedelta(days=6)
print(start)
print(end)
Now we will find months first and last date based on current date/time
start = datetime.now().replace(day=1)
end = datetime.now().replace(day=monthrange(datetime.now().year, datetime.now().month)[1])
print(start)
print(end)
end = datetime.now().replace(day=monthrange(datetime.now().year, datetime.now().month)[1])
print(start)
print(end)
Complete code:
from datetime import datetime, timedelta
from calendar import monthrange
today = datetime.now()
print('Today')
print(today)
weekstart = datetime.now() - timedelta(days=datetime.now().weekday())
weekend = weekstart + timedelta(days=6)
print('Week Start:')
print(weekstart)
print('Week End:')
print(weekend)
monthstart = datetime.now().replace(day=1)
monthend = datetime.now().replace(day=monthrange(datetime.now().year, datetime.now().month)[1])
print('Month Start:')
print(monthstart)
print('Month End:')
print(monthend)
Output:from calendar import monthrange
today = datetime.now()
print('Today')
print(today)
weekstart = datetime.now() - timedelta(days=datetime.now().weekday())
weekend = weekstart + timedelta(days=6)
print('Week Start:')
print(weekstart)
print('Week End:')
print(weekend)
monthstart = datetime.now().replace(day=1)
monthend = datetime.now().replace(day=monthrange(datetime.now().year, datetime.now().month)[1])
print('Month Start:')
print(monthstart)
print('Month End:')
print(monthend)
Today
2019-05-23 16:40:51.808967
Week Start:
2019-05-20 16:40:51.809071
Week End:
2019-05-26 16:40:51.809071
Month Start:
2019-05-01 16:40:51.809179
Month End:
2019-05-31 16:40:51.809202
2019-05-23 16:40:51.808967
Week Start:
2019-05-20 16:40:51.809071
Week End:
2019-05-26 16:40:51.809071
Month Start:
2019-05-01 16:40:51.809179
Month End:
2019-05-31 16:40:51.809202
Comments
Post a Comment