I'm hoping to create a program that takes todays date and a given date in the future and finds the difference in days between those two dates. I'm not too sure as to how I would go about doing this and I have very little experience using datetime.
From what I've been trying and reading up, I need to import datetime, and then grab todays date. After that, I need to take an input from the user for the day, month and year that they want in the future, and to make a check that the current year is less than the future year. After that, I'll need to do a calculation in the difference in days between them and print that to the screen.
Any help would be very much appreciated.
Many Thanks
here a hint for you small program using datetime and time:
>>> import time
>>> import datetime
>>> today_time = time.time()
>>> today_time
1415848116.311676
>>> today_time = datetime.datetime.fromtimestamp(today_time)
>>> today_time
datetime.datetime(2014, 11, 13, 8, 38, 36, 311676)
>>> future_time = input("Enter Year,month,day separeted by space:")
Enter Year,month,day separeted by space:2015 06 24
>>> year,month,day = future_time.split()
>>> diff = datetime.datetime(int(year),int(month),int(day)) - today_time
>>> diff.days
222
you can use datetime.date but instead asking user current date, you can have it from the system using time.time
Related
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
I would like to get the current time in Python and assign them into variables like year, month, day, hour, minute. How can this be done in Python 2.7?
The datetime module is your friend:
import datetime
now = datetime.datetime.now()
print(now.year, now.month, now.day, now.hour, now.minute, now.second)
# 2015 5 6 8 53 40
You don't need separate variables, the attributes on the returned datetime object have all you need.
Here's a one-liner that comes in just under the 80 char line max.
import time
year, month, day, hour, min = map(int, time.strftime("%Y %m %d %H %M").split())
The datetime answer by tzaman is much cleaner, but you can do it with the original python time module:
import time
strings = time.strftime("%Y,%m,%d,%H,%M,%S")
t = strings.split(',')
numbers = [ int(x) for x in t ]
print numbers
Output:
[2016, 3, 11, 8, 29, 47]
By unpacking timetuple of datetime object, you should get what you want:
from datetime import datetime
n = datetime.now()
t = n.timetuple()
y, m, d, h, min, sec, wd, yd, i = t
Let's see how to get and print day,month,year in python from current time:
import datetime
now = datetime.datetime.now()
year = '{:02d}'.format(now.year)
month = '{:02d}'.format(now.month)
day = '{:02d}'.format(now.day)
hour = '{:02d}'.format(now.hour)
minute = '{:02d}'.format(now.minute)
day_month_year = '{}-{}-{}'.format(year, month, day)
print('day_month_year: ' + day_month_year)
result:
day_month_year: 2019-03-26
For python 3
import datetime
now = datetime.datetime.now()
print(now.year, now.month, now.day, now.hour, now.minute, now.second)
import time
year = time.strftime("%Y") # or "%y"
You can use gmtime
from time import gmtime
detailed_time = gmtime()
#returns a struct_time object for current time
year = detailed_time.tm_year
month = detailed_time.tm_mon
day = detailed_time.tm_mday
hour = detailed_time.tm_hour
minute = detailed_time.tm_min
Note: A time stamp can be passed to gmtime, default is current time as
returned by time()
eg.
gmtime(1521174681)
See struct_time
Three libraries for accessing and manipulating dates and times, namely datetime, arrow and pendulum, all make these items available in namedtuples whose elements are accessible either by name or index. Moreover, the items are accessible in precisely the same way. (I suppose if I were more intelligent I wouldn't be surprised.)
>>> YEARS, MONTHS, DAYS, HOURS, MINUTES = range(5)
>>> import datetime
>>> import arrow
>>> import pendulum
>>> [datetime.datetime.now().timetuple()[i] for i in [YEARS, MONTHS, DAYS, HOURS, MINUTES]]
[2017, 6, 16, 19, 15]
>>> [arrow.now().timetuple()[i] for i in [YEARS, MONTHS, DAYS, HOURS, MINUTES]]
[2017, 6, 16, 19, 15]
>>> [pendulum.now().timetuple()[i] for i in [YEARS, MONTHS, DAYS, HOURS, MINUTES]]
[2017, 6, 16, 19, 16]
This is an older question, but I came up with a solution I thought others might like.
def get_current_datetime_as_dict():
n = datetime.now()
t = n.timetuple()
field_names = ["year",
"month",
"day",
"hour",
"min",
"sec",
"weekday",
"md",
"yd"]
return dict(zip(field_names, t))
timetuple() can be zipped with another array, which creates labeled tuples. Cast that to a dictionary and the resultant product can be consumed with get_current_datetime_as_dict()['year'].
This has a little more overhead than some of the other solutions on here, but I've found it's so nice to be able to access named values for clartiy's sake in the code.
I would like to write a function that takes a date entered by the user, stores it with the shelve function and prints the date thirty days later when called.
I'm trying to start with something simple like:
import datetime
def getdate():
date1 = input(datetime.date)
return date1
getdate()
print(date1)
This obviously doesn't work.
I've used the answers to the above question and now have that section of my program working! Thanks!
Now for the next part:
I'm trying to write a simple program that takes the date the way you instructed me to get it and adds 30 days.
import datetime
from datetime import timedelta
d = datetime.date(2013, 1, 1)
print(d)
year, month, day = map(int, d.split('-'))
d = datetime.date(year, month, day)
d = dplanted.strftime('%m/%d/%Y')
d = datetime.date(d)+timedelta(days=30)
print(d)
This gives me an error:
year, month, day = map(int, d.split('-'))
AttributeError: 'datetime.date' object has no attribute 'split'
Ultimately what I want is have 01/01/2013 + 30 days and print 01/30/2013.
Thanks in advance!
The input() method can only take text from the terminal. You'll thus have to figure out a way to parse that text and turn it into a date.
You could go about that in two different ways:
Ask the user to enter the 3 parts of a date separately, so call input() three times, turn the results into integers, and build a date:
year = int(input('Enter a year'))
month = int(input('Enter a month'))
day = int(input('Enter a day'))
date1 = datetime.date(year, month, day)
Ask the user to enter the date in a specific format, then turn that format into the three numbers for year, month and day:
date_entry = input('Enter a date in YYYY-MM-DD format')
year, month, day = map(int, date_entry.split('-'))
date1 = datetime.date(year, month, day)
Both these approaches are examples; no error handling has been included for example, you'll need to read up on Python exception handling to figure that out for yourself. :-)
Thanks. I have been trying to figure out how to add info to datetime.datetime(xxx) and this explains it nicely. It's as follows
datetime.datetime(year,month, day, hour, minute, second) with parameters all integer. It works!
Use the dateutils module
from dateutil import parser
date = parser.parse(input("Enter date: "))
you can also use
import datetime
time_str = input("enter time in this format yyyy-mm-dd")
time=datetime.datetime.strptime(time_str, "%Y-%m-%d")
datetime.datetime.strptime() strips the given string in the format you give it.
Check the library as
import datetime
and follow syntax
date = datetime.datetime(2013, 1, 1)
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
Is there a library in python that can produce date dimensions given a certain day? I'd like to use this for data analysis. Often I have a time series of dates, but for aggregation purposes I'd like to be able to quickly produce dates associated with that day - like first date of month, first day in week, and the like.
I think I could create my own, but if there is something out there already it'd be nice.
Thanks
Have a look at dateutil.
The recurrence rules and relative deltas are what you want.
For example, if you wanted to get last monday:
import dateutil.relativedelta as rd
import datetime
last_monday = datetime.date.today() + rd.relativedelta(weekday=rd.MO(-1))
time and datetime modules
For some of your purposes you can use time module with strftime() method or date module with its strftime() method. It allows you to pull, among other data:
number of the week of the year,
number of the weekday (you can also use weekday() method for getting weekday number between 0 for Monday and 6 for Sunday),
year,
month,
Which will suffice to calculate first day of the month, first day of the week and some other data.
Examples
To pull the data you need, do just:
to pull the number of the day of the week
>>> from datetime import datetime
>>> datetime.now().weekday()
6
to pull the first day of the month use replace() function of datetime object:
>>> from datetime import datetime
>>> datetime.now()
datetime.datetime(2012, 3, 3, 21, 41, 20, 953000)
>>> first_day_of_the_month = datetime.now().replace(day=1)
>>> first_day_of_the_month
datetime.datetime(2012, 3, 1, 21, 41, 20, 953000)
EDIT: As J.F. Sebastian suggested within comments, datetime objects have weekday() methods, which makes using int(given_date.strftime('%w')) rather pointless. I have updated the answer above.