the emplyee number is composed of year and month and 3 digit control number how to know the number of years they works if we base on todays date? Employee1 201011003, eployee2 200605015
You can use datetime library like this:
from datetime import date
date_str = '201011003'
year = int(date_str[0:4])
month = int(date_str[4:6])
d = date(year, month, 1)
year_delta = (date.today() - d).days // 365
print(year_delta)
You can use datetime.strptime to read the date string into a datetime object. By subtracting two datetime objects you'll get back a timedelta object, which you can use to compute the years the employee has been there.
from datetime import datetime
def get_date(s):
return datetime.strptime(s[:6], '%Y%m')
Examples
>>> get_date('201011003')
datetime.datetime(2010, 11, 1, 0, 0)
>>> get_date('200605015')
datetime.datetime(2006, 5, 1, 0, 0)
Depending on the precision you want, you can approximate the number of years the employee has been there like
def get_years(s):
start = datetime.strptime(s[:6], '%Y%m')
now = datetime.now()
return (now - start).days / 365.25
>>> get_years('201011003')
9.527720739219713
>>> get_years('200605015')
14.03148528405202
To get very accurate results, I suggest you to use the dateutil package. It contains a super powerful function called relativedelta that is going to give you the years, months and days that have passed since the day you are interested in, considering leap years (instead of just days, as the datetime.timedelta does).
Also, just as CoryKramer did, we can use the strptime function to parse the date from the employee's codes you have.
import datetime as dt
from dateutil.relativedelta import relativedelta
employee = '201011003'
date_joined = dt.datetime.strptime(employee[:6], '%Y%m')
result = relativedelta(dt.datetime.today(), date_joined)
print('The employee has been working for {} years, {} months and {} days'.format(
result.years, result.months, result.days))
Outputs
The employee has been working for 9 years, 6 months and 11 days
Related
I want to get last three months from todays date in year-mon format. For example if todays date is 2021-08-04 then I want list of last three months as -
["2021-05", "2021-06", "2021-07"]
I have no idea how to start with this. Any help will be appreciated.
use dateutil's relativedelta to get consistent results, as not all months have equal number of days. E.g.
from datetime import datetime
from dateutil.relativedelta import relativedelta
NOW = datetime.now() # reference date
delta = relativedelta(months=-1) # delta in time
n = 3 # how many steps
fmt = lambda dt: dt.strftime("%Y-%m") # formatter; datetime object to string
l = sorted((fmt(NOW+delta*i) for i in range(1, n+1)))
# l
# ['2021-05', '2021-06', '2021-07']
PaymentDate = datetime.now().timetuple().tm_yday + 7
NS_Date_Text = driver.find_element(By.ID, "custrecord_ps_inv_date_val").text
basedate = datetime.strptime(NS_Date_Text, '%m/%d/%Y')
basedate1 = datetime.timetuple(basedate).tm_yday
DaysUntilPayment = PaymentDate - basedate1
This code works so far for the year of 2019. But, I am not sure how to account for 2020 or 2018
So, I am converting the current date to the number of day in the year (January 1 would be 1 and December 31 would be 365/366) then adding 7 to that number. This is the Payment Date.
Then, I am finding a date on the webpage(BaseDate) and converting that number to the day of the year.
Then subtracting those two numbers.
I am not sure how well it's going to work if the current date is: January 10, 2020 (10th day) + 7 = day 17. But the base date is 12/28/2019 (362nd day).
The number I will get would be 345 and that's way too far ahead, while I need the number(DaysUntilPayment) to be 20.
I hope I was able to explain this well. Please lmk if you have any questions!
You are making this way more complicated than it needs to be. Python's datetime.date() objects know how to handle deltas themselves; if you subtract two date() objects you get a timedelta() instance, which has a .days attribute.
Next, you can create your own timedelta() object to add 7 days to 'today':
from datetime import date, timedelta
# 7 days from today
payment_date = date.today() + timedelta(days=7)
# find base date on the webpage
ns_date_text = driver.find_element(By.ID, "custrecord_ps_inv_date_val").text
basedate = datetime.strptime(ns_date_text, '%m/%d/%Y').date()
# calculate the difference in days between these two dates
# date - date = timedelta, so take the .days attribute from that result
days_until_payment = (payment_date - basedate).days
Note that I used only the date component of the datetime.strptime() result. You can do all this with datetime objects too, but then you may have to worry about timezones and such, and it's just easier not to have to do that.
These operations take care of details such as handling years, and more importantly, handling leap years:
>>> from datetime import date, datetime, timedelta
>>> payment_date = date(2020, 2, 22) + timedelta(days=7)
>>> payment_date # this is February 29th, a leap day!
datetime.date(2020, 2, 29)
>>> basedate = datetime.strptime("12/31/2019", '%m/%d/%Y').date # last day of 2019
>>> payment_date - basedate
datetime.timedelta(days=60)
>>> (payment_date - basedate).days # February 29th is 60 days later
60
For further details, see the datetime.date documentation, which has a Supported operations section, with:
date2 = date1 + timedelta
date2 is timedelta.days days removed from date1
timedelta = date1 - date2
This is exact, and cannot overflow. timedelta.seconds and timedelta.microseconds are 0, and date2 + timedelta == date1 after.
Please what's wrong with my code:
import datetime
d = "2013-W26"
r = datetime.datetime.strptime(d, "%Y-W%W")
print(r)
Display "2013-01-01 00:00:00", Thanks.
A week number is not enough to generate a date; you need a day of the week as well. Add a default:
import datetime
d = "2013-W26"
r = datetime.datetime.strptime(d + '-1', "%Y-W%W-%w")
print(r)
The -1 and -%w pattern tells the parser to pick the Monday in that week. This outputs:
2013-07-01 00:00:00
%W uses Monday as the first day of the week. While you can pick your own weekday, you may get unexpected results if you deviate from that.
See the strftime() and strptime() behaviour section in the documentation, footnote 4:
When used with the strptime() method, %U and %W are only used in calculations when the day of the week and the year are specified.
Note, if your week number is a ISO week date, you'll want to use %G-W%V-%u instead! Those directives require Python 3.6 or newer.
In Python 3.8 there is the handy datetime.date.fromisocalendar:
>>> from datetime import date
>>> date.fromisocalendar(2020, 1, 1) # (year, week, day of week)
datetime.date(2019, 12, 30, 0, 0)
In older Python versions (3.7-) the calculation can use the information from datetime.date.isocalendar to figure out the week ISO8601 compliant weeks:
from datetime import date, timedelta
def monday_of_calenderweek(year, week):
first = date(year, 1, 1)
base = 1 if first.isocalendar()[1] == 1 else 8
return first + timedelta(days=base - first.isocalendar()[2] + 7 * (week - 1))
Both works also with datetime.datetime.
To complete the other answers - if you are using ISO week numbers, this string is appropriate (to get the Monday of a given ISO week number):
import datetime
d = '2013-W26'
r = datetime.datetime.strptime(d + '-1', '%G-W%V-%u')
print(r)
%G, %V, %u are ISO equivalents of %Y, %W, %w, so this outputs:
2013-06-24 00:00:00
Availabe in Python 3.6+; from docs.
import datetime
res = datetime.datetime.strptime("2018 W30 w1", "%Y %W w%w")
print res
Adding of 1 as week day will yield exact current week start. Adding of timedelta(days=6) will gives you the week end.
datetime.datetime(2018, 7, 23)
If anyone is looking for a simple function that returns all working days (Mo-Fr) dates from a week number consider this (based on accepted answer)
import datetime
def weeknum_to_dates(weeknum):
return [datetime.datetime.strptime("2021-W"+ str(weeknum) + str(x), "%Y-W%W-%w").strftime('%d.%m.%Y') for x in range(-5,0)]
weeknum_to_dates(37)
Output:
['17.09.2021', '16.09.2021', '15.09.2021', '14.09.2021', '13.09.2021']
In case you have the yearly number of week, just add the number of weeks to the first day of the year.
>>> import datetime
>>> from dateutil.relativedelta import relativedelta
>>> week = 40
>>> year = 2019
>>> date = datetime.date(year,1,1)+relativedelta(weeks=+week)
>>> date
datetime.date(2019, 10, 8)
Another solution which worked for me that accepts series data as opposed to strptime only accepting single string values:
#fw_to_date
import datetime
import pandas as pd
# fw is input in format 'YYYY-WW'
# Add weekday number to string 1 = Monday
fw = fw + '-1'
# dt is output column
# Use %G-%V-%w if input is in ISO format
dt = pd.to_datetime(fw, format='%Y-%W-%w', errors='coerce')
Here's a handy function including the issue with zero-week.
I am trying to get the date delta by subtracting today's date from the nth day of the next month.
delta = nth_of_next_month - todays_date
print delta.days
How do you get the date object for the 1st (or 2nd, 3rd.. nth) day of the next month. I tried taking the month number from the date object and increasing it by 1. Which is obviously a dumb idea because 12 + 1 = 13. I also tried adding one month to today and tried to get to the first of the month. I am sure that there is a much more efficient way of doing this.
The dateutil library is useful for this:
from dateutil.relativedelta import relativedelta
from datetime import datetime
# Where day is the day you want in the following month
dt = datetime.now() + relativedelta(months=1, day=20)
This should be straightforward unless I'm missing something in your question:
import datetime
now = datetime.datetime.now()
nth_day = 5
next_month = now.month + 1 if now.month < 12 else 1 # February
year = now.year if now.month < 12 else now.year+1
nth_of_next_month = datetime.datetime(year, next_month, nth_day)
print(nth_of_next_month)
Result:
2014-02-05 00:00:00
Using dateutil as suggested in another answer is a much better idea than this, though.
Another alternative is to use delorean library:
Delorean is a library that provides easy and convenient datetime
conversions in Python.
>>> from delorean import Delorean
>>> d = Delorean()
>>> d.next_month()
Delorean(datetime=2014-02-15 18:51:14.325350+00:00, timezone=UTC)
>>> d.next_month().next_day(2)
Delorean(datetime=2014-02-17 18:51:14.325350+00:00, timezone=UTC)
My approach to calculating the next month without external libraries:
def nth_day_of_next_month(dt, n):
return dt.replace(
year=dt.year + (dt.month // 12), # +1 for december, +0 otherwise
month=(dt.month % 12) + 1, # december becomes january
day=n)
This works for both datetime.datetime() and datetime.date() objects.
Demo:
>>> import datetime
>>> def nth_day_of_next_month(dt, n):
... return dt.replace(year=dt.year + (dt.month // 12), month=(dt.month % 12) + 1, day=n)
...
>>> nth_day_of_next_month(datetime.datetime.now(), 4)
datetime.datetime(2014, 2, 4, 19, 20, 51, 177860)
>>> nth_day_of_next_month(datetime.date.today(), 18)
datetime.date(2014, 2, 18)
Without using any external library, this can be achived as follows
from datetime import datetime, timedelta
def nth_day_of_next_month(n):
today = datetime.now()
next_month_dt = today + timedelta(days=32-today.day)
return next_month_dt.replace(day=n)
I'm working on a simple program to tell an individual how long they have been alive.
I know how to get the current date, and get their birthday. The only problem is I have no way of subtracting the two, I know a way of subtracting two dates, but unfortunately it does not include hours, minutes, or seconds.
I am looking for a method that can subtract two dates and return the difference down to the second, not merely the day.
from datetime import datetime
birthday = datetime(1988, 2, 19, 12, 0, 0)
diff = datetime.now() - birthday
print diff
# 8954 days, 7:03:45.765329
Use UTC time otherwise age in seconds can go backwards during DST transition:
from datetime import datetime
born = datetime(1981, 12, 2) # provide UTC time
age = datetime.utcnow() - born
print(age.total_seconds())
You also can't use local time if your program runs on a computer that is in a different place (timezone) from where a person was born or if the time rules had changed in this place since birthday. It might introduce several hours error.
If you want to take into account leap seconds then the task becomes almost impossible.
When substracting two datetime objects you will get a new datetime.timedelta object.
from datetime import datetime
x = datetime.now()
y = datetime.now()
delta = y - x
It will give you the time difference with resolution to microsencods.
For more information take a look at the official documentation.
Create a datetime.datetime from your date:
datetime.datetime.combine(birthdate, datetime.time())
Now you can subtract it from datetime.datetime.now().
>>> from datetime import date, datetime, time
>>> bday = date(1973, 4, 1)
>>> datetime.now() - datetime.combine(bday, time())
datetime.timedelta(14392, 4021, 789383)
>>> print datetime.now() - datetime.combine(bday, time())
14392 days, 1:08:13.593813
import datetime
born = datetime.date(2002, 10, 31)
today = datetime.date.today()
age = today - born
print(age.total_seconds())
Output: 463363200.0
Since DateTime.DateTime is an immutable type method like these always produce a new object the difference of two DateTime object produces a DateTime.timedelta type:
from datetime import date,datetime,time,timedelta
dt=datetime.now()
print(dt)
dt2=datetime(1997,7,7,22,30)
print(dt2)
delta=dt-dt2
print(delta)
print(int(delta.days)//365)
print(abs(12-(dt2.month-dt.month)))
print(abs(dt.day))
The output timedelta(8747,23:48:42.94) or what ever will be days when u test the code indicates that the time delta encodes an offset of 8747 days and 23hour and 48 minute ...
The Output
2021-06-19 22:27:36.383761
1997-07-07 22:30:00
8747 days, 23:57:36.383761
23 Year
11 Month
19 Day