python Datetime - extract year and month - python-3.x

How to extract month and year from a string in DateTime stamp format?
sales_close_7 = 2018-12-07

import datetime
sales_close_7 = '2018-12-07'
date_object = datetime.datetime.strptime(sales_close_7, '%Y-%m-%d').date()
print(date_object.year)
Output: 2018
print(date_object.month)
Output: 12

Related

Get last day of week of a given date

Given any day of the year, such as today, I would have the last day of the current week.
For example, current day is 2021-12-27 (Monday), so the last day of this week is 2022-01-01 (Saturday), because of isoWeek in my systems starts from Sundays.
from datetime import datetime
dt = datetime.now()
print(dt) # 2021-12-27 12:57:57.004108
last_day_of_week = get_ldow(dt)
print(last_day_of_week) # 2022-01-01 00:00:00.000000
How get_ldow(df) could be implemented?
Import of datatime can be tricky.
import datetime
dt = datetime.datetime.today() # 2021-12-27 13:40:10.204296
def get_ldow(dt_input):
return dt_input + datetime.timedelta(days=(6 - dt_input.isoweekday() % 7))
last_day_of_week = get_ldow(dt)
print(last_day_of_week) # 2022-01-01 13:40:10.204296

month begining dates 2 mnths back

I have dates in yyyy-dd-mm in a column(col 1).(type = pandas.core.series.Series and dtypes=datetime64[ns]). I need begining of the month date for 2 months prior(col 2)
col 1 col2
2021-01-07 2020-01-05
I have been trying to use timedelta & relative timedelta , but not working. can anyone help?
Since timedelta does not have months parameter, you can use dateutil module instead:
from dateutil.relativedelta import relativedelta
df['col2'] = df['col1'].apply(lambda x: x - relativedelta(months=2))

Datetime conversion format

I converted the datetime from a format '2018-06-22T09:38:00.000-04:00'
to pandas datetime format
i tried to convert using pandas and got output but the output is
o/p: 2018-06-22 09:38:00-04:00
date = '2018-06-22T09:38:00.000-04:00'
dt = pd.to_datetime(date)
expected result: 2018-06-22 09:38
actual result: 2018-06-22 09:38:00-04:00
There is timestamps with timezones, so if convert to UTC by Timestamp.tz_convert, times are changed:
date = '2018-06-22T09:38:00.000-04:00'
dt = pd.to_datetime(date).tz_convert(None)
print (dt)
2018-06-22 13:38:00
So possible solution is remove last 6 values in datetimes:
dt = pd.to_datetime(date[:-6])
print (dt)
2018-06-22 09:38:00

Python - Calculate date difference in months

I need to get the difference between the days in months and days (eg. 3months 20days).
from datetime import datetime
from dateutil import relativedelta
date1 = datetime.strptime('2019-06-23', "%Y-%m-%d")
date2 = datetime.strptime('2018-04-17', '%Y-%m-%d')
r = relativedelta.relativedelta(date1, date2)
print(r)
This gives me result like relativedelta(years=+1, months=+2, days=+6) whereas I need result like 14 months 6 days
Thank you
Incorporate a minor modification to get the answer.
print(r.years, 'years,', r.months,'months and', r.days, 'days')

Convert string formatted date to epoch

How to convert string formatted date to epoch format. Like the give date is in this format 2018, June 12th how to convert it to epoch in python?
You can use python datetime for all your date time related conversions.
fstring = "%Y, %B %d"
end = {"th" : fstring + "th", "rd": fstring + "rd"}
days = ["2018, June 12th", "2018, June 3rd"]
for day in days:
fstr = end["rd"] if day.endswith("rd") else end["th"]
print(datetime.datetime.strptime(day, fstr).timestamp())
1528741800.0
1527964200.0
More info here

Resources