import datetime
currentTime = datetime.datetime.now()
print ("Current date and time is:", currentTime.strftime("%Y-%m-%d %H:%M:%S"))
Output is:
Current date and time is: 2016-10-18 22:31:21
I want it to be:- without using another print statement may be /n which is not working:-
Current date and time is:
2016-10-18 22:31:21
Help?
Add a newline character ('\n') to your print:
print("Current date and time is:\n", currentTime.strftime("%Y-%m-%d %H:%M:%S"))
EDIT
As #StevenRumbalski points out, it would be better to use string concatenation with +:
print("Current date and time is:\n" + currentTime.strftime("%Y-%m-%d %H:%M:%S"))
to avoid the indentation that results from my previous code.
You can pass whatever separator you like with the sep keyword sep="\n":
In [1]: import datetime
...: currentTime = datetime.datetime.now()
...: print ("Current date and time is:", currentTime.strftime("%Y-%m-%d %H:%M
...: :%S"),sep="\n")
...:
Current date and time is:
2016-10-18 18:21:25
If you wanted multiple newlines:
In [4]: print ("Current date and time is:", currentTime.strftime("%Y-%m-%d %H:%M
...: :%S"), sep="\n" * 3)
Current date and time is:
2016-10-18 18:21:25
Newline character is \n not /n
Related
I've reviewed this many times and don't understand why the str2 case won't convert correct? This is being run in Python 3.8.
from datetime import datetime
import time
print(time.tzname)
date_time_str1 = '(2021,10,4) (19,36,21)'
date_time_str2 = 'Mon Oct 4 11:13:08 2021'
print(date_time_str1)
print(date_time_str2)
date_time_obj = datetime.strptime(date_time_str1, '(%Y,%m,%d) (%H,%M,%S)')
print ("The date is", date_time_obj)
date_time_obj = datetime.strptime(date_time_str2, '%A %B %d %H:%M:%S %Y')
print ("The date is", date_time_obj)
You should use '%a %b %d %H:%M:%S %Y' because your day and month names are abbreviated.
Say for the year of 2020, how do I iterate through the days in the months so that my outcome would be in the following format:
Jan1
Jan2
Jan3
....
Jan31
Feb1
I've tried so many things online but I couldnt find an answer. Please help :(
Both of these methods will handle leap years correctly out of the box.
Using a simple while loop:
from datetime import datetime, timedelta
def iter_days(year):
dt = datetime(year, 1, 1)
while dt.year == year:
yield dt
dt += timedelta(days=1)
Using date rules:
from datetime import datetime
from dateutil.rrule import rrule, DAILY
def iter_days(year):
first_date = datetime(year, 1, 1)
last_date = datetime(year, 12, 31)
return rrule(DAILY, dtstart=first_date, until=last_date)
Both would be used the same:
for dt in iter_days(2020):
print(dt.strftime('%b%-d'))
The format string '%b%-d' will give you the format you specified in your question. I don't know if that was a requirement or not.
This is crude but gets what you want for 2020. You'll need to change 366 to 365 for non-leap-years.
#!/usr/bin/python3
import datetime
startDate = '2020-01-01'
start = datetime.datetime.strptime(startDate, '%Y-%m-%d')
for dayNum in range(0,366):
dayOfYear = start + datetime.timedelta(days=dayNum)
print(dayOfYear.strftime('%b %d, %Y'))
The calendar module offers quite a bit of functionality.
Here is a solution that works for any given year
import calendar as cal
for mi in range(1,13):
_, days = cal.monthrange(2020, mi)
for d in range(1, days+1):
print(cal.month_name[mi], d)
After searching around the web got the below two ways to get the age of a person.
Just curious to Know if there is better synthetic way of calculating & writing it in 3.x version of python.
First way around ...
$ cat birth1.py
#!/grid/common/pkgs/python/v3.6.1/bin/python3
import datetime
year = datetime.datetime.now().year # getting current year from the system
year_of_birth = int(input("Enter Your Birth Year: "))
print("You are %i Year Old" % (year - year_of_birth))
The Result produced..
$ ./birth1.py
Enter Your Birth Year: 1981
You are 37 Year Old
Second way around ....
$ cat birth2.py
#!/grid/common/pkgs/python/v3.6.1/bin/python3
from datetime import datetime, date
print("Your date of birth (dd/mm/yyyy)")
date_of_birth = datetime.strptime(input("Please Put your age here: "), "%d/%m/%Y")
def calculate_age(born):
today = date.today()
return today.year - born.year - ((today.month, today.day) < (born.month, born.day))
age = calculate_age(date_of_birth)
print("You are %i Year Old." % (age))
The Result produces..
$ ./birth2.py
Your date of birth (dd/mm/yyyy)
Please Put your age here: 22/09/2015
You are 2 Year Old.
Take advantage of timedelta.
import datetime as dt
def years_ago(start: str):
sec_per_year = 365.24 * 24 * 60 * 60
delta = dt.datetime.now() - dt.datetime.strptime(start, '%d/%m/%Y')
return delta.total_seconds() / sec_per_year
if __name__ == '__main__':
print(int(years_ago(input('What is your date of birth (dd/mm/yyyy) ? '))))
I have dataframe with timestamp values and i want to round off the timestamp to upper minute.
But i am not getting the desired output.
I have used the following link to do the same:
[1]: http://stackoverflow.com/questions/32344533/how-do-i-round-datetime-column-to-nearest-quarter-hour/32344636
how can i do that using pandas?
example: output:
05:06:34 05:07
05:09:43 05:10
You can write a function that will round up to the nearest minute:
Code:
import datetime as dt
def round_up_to_minute(timestamp):
return timestamp + dt.timedelta(
seconds=60-timestamp.second,
microseconds=-timestamp.microsecond)
Test Code:
To apply it to a dataframe, you can do something like:
now = dt.datetime.now()
now_plus = now + dt.timedelta(minutes=1)
df = pd.DataFrame(data=[[now, now], [now_plus, now_plus]],
columns=['datetime', 'datetime_rounded'])
df['datetime_rounded'] = df['datetime_rounded'].apply(round_up_to_minute)
print(df)
Results:
datetime datetime_rounded
0 2017-03-06 07:36:54.794 2017-03-06 07:37:00
1 2017-03-06 07:37:54.794 2017-03-06 07:38:00
Some time before September 2022 pandas incorporated DatetimeIndex.ceil().
dt_index = pd.to_datetime(['1970-01-01 05:06:34','1970-01-01 05:09:43'])
print(dt_index)
print(dt_index.ceil('1min'))
Outputs
DatetimeIndex(['1970-01-01 05:06:34', '1970-01-01 05:09:43'], dtype='datetime64[ns]', freq=None)
DatetimeIndex(['1970-01-01 05:07:00', '1970-01-01 05:10:00'], dtype='datetime64[ns]', freq=None)
DatetimeIndex also has floor() and round().
I'm trying to get two dates as input and convert is epoch time, but i need the two different dates given as input to be validated in correct format else recursively ask for correct input.
from datetime import date
import datetime
start_date = datetime.datetime.strptime(raw_input('Enter Start date in the format DD-MM-YYYY: '), '%d-%m-%Y')
end_date = datetime.datetime.strptime(raw_input('Enter Start date in the format DD-MM-YYYY: '), '%d-%m-%Y')
epoch_date = datetime.datetime(1970,1,1)
diff1 = (start_date - epoch_date).days
diff2 = (end_date - epoch_date).days
epoch1 = (diff1 * 86400)
epoch2 = (diff2 * 86400)
print('\nPTime_Start: %i' % diff1),
print("&"),
print('PTime_End: %i' % diff2)
print('Epoch_Start: %i' % epoch1),
print("&"),
print('Epoch_End: %i' % epoch2)
First of all, you are using Python 3.x and Python 3.x does not have any function that is called "raw_input()". It has been changed to "input()".
def take_date_input():
input_date = input('Enter date in the format DD-MM-YYYY: ')
try:
one_date = datetime.datetime.strptime(input_date, '%d-%m-%Y')
except ValueError:
return take_date_input()
return one_date
You can do this if you really want recursiveness in your code but it would be better with while loop.