Set the desired date format to file name in Python - python

I want to specify the date of the desired format as a file name in this way
;
During [2019-10-01 09:00 ~ 2019-10-02 08:59:59]
Save data to 191001-09.txt
I have no idea about this. I could only follow simple code.
Please let me know how to fix it :
def timeStamped (fname, fmt = '19% m% d-% H {fname} '):
return datetime.datetime.now (). strftime (fmt) .format (fname = fname)
with open (timeStamped ('. txt'), 'a') as f_last:
f_last.write ('data')

Question: Conditional file name from datetime.now()
Import the required objects
datetime
timedelta
from datetime import datetime, timedelta
Define a function that gets the desired file name from a datetime.date object:
def fname_from_date(date):
# Rule 09:00:00 ~ day + 1 08:59:59
midnight = date.replace(hour=0, minute=0, second=0)
begin_of_day = date.replace(hour=9, minute=0, second=0)
end_of_day = date.replace(hour=8, minute=59, second=59)
# Are we between 'midnight' and 'end_of_day'
if date >= midnight and date <= end_of_day:
date = date - timedelta(days=1)
print('\tNext day -1: {}'.format(date))
# 191001-09.txt
fname = date.strftime('%Y%m%d-09')
return fname
Test the function def fname_from_date(... with static dates.
This requires to create a datetime.date object from datestr.
for datestr in ['2019-10-01 09:00:00',
'2019-10-01 11:01:11',
'2019-10-02 07:07:07',
'2019-10-02 08:59:59']:
date = datetime.strptime(datestr, '%Y-%m-%d %H:%M:%S')
print(date)
fname = '{}.txt'.format(fname_from_date(date))
print('\t{}'.format(fname))
Output:
2019-10-01 09:00:00
20191001-09.txt
2019-10-01 11:01:11
20191001-09.txt
2019-10-02 07:07:07
Next day -1: 2019-10-01 07:07:07
20191001-09.txt
2019-10-02 08:59:59
Next day -1: 2019-10-01 08:59:59
20191001-09.txt
Usage:
fname = '{}.txt'.format(fname_from_date(datetime.now()))

Related

How can I make a list of last two digits of year plus month

Can I get some help to create a list of days and months in the folowing format:
collection = ['2108', '2109', '2110', '2111', '2112', '2201']
I am trying in this way:
def make_collections(start_date: Date, end_date: Date):
result = []
date = start_date
while True:
if start_date >= end_date:
return result
date = date.strftime('%y%m%d%H%M%S')
result.append(date[:4])
date = (date.strptime(date, '%y%m%d%H%M%S')) + timedelta(days=1)
# test = MakeDataFrame()
# test.run()
if __name__ == '__main__':
start = datetime.now() - timedelta(days=365)
print(make_collections(start, datetime.now()))
But it doesn't work.
I want to give a start date and end date as an argument in function and make a list as I mentioned above with year and month.
Can I get some help to make a a simple function with start and end date as an arguments?
Thanks
I revised your code a little bit, so that the code will print what you expected. I used dateutil.relativedelta module because timedelta provide only day-based delta. dateutil.relativedelta support to calculate month and year differences.
from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta
def make_collections(start_date, end_date):
result = []
while start_date <= end_date:
result.append(str(start_date.year)[2:] + str(start_date.month).zfill(2))
start_date += relativedelta(months=1)
return result
if __name__ == '__main__':
start = datetime.now() - timedelta(days=365)
print(make_collections(start, datetime.now()))
#['2101', '2102', '2103', '2104', '2105', '2106', '2107', '2108', '2109', '2110', '2111', '2112', '2201']

compare date with past day

x=['2020-05-12 20:16', '2020-05-12 20:16', '2020-05-10 20:11', '2020-05-10 20:07', '2020-05-11 20:03', '2020-05-8 20:02', '2020-05-8 20:02', '2020-05-9 20:02',]
#staticmethod
def compare_time(post_time):
date_object = datetime.strptime(post_time, "%Y-%m-%d %H:%M")
past = datetime.now() - date_object
How can I edit my function so that it returns True if the date not older than yesterday (within 24 hours of current time) else returns False, I feel I am half way there but not sure what to do next.
You need to quantify the difference between 2 datetime object, timedelta is here that
A timedelta object represents a duration, the difference between two dates or times.
You want our duration to be lower than 24h/1d so you need < timedelta(days=1) or < timedelta(hours=24)
def compare_time(post_time):
date_object = datetime.strptime(post_time, "%Y-%m-%d %H:%M")
past = datetime.now() - date_object
return past < timedelta(days=1) # from datetime import timedelta
test the difference datetime.now() - date_object against a timedelta of 1 day:
from datetime import datetime, timedelta
x = ['2020-05-12 20:16', '2020-05-12 20:16', '2020-05-10 20:11',
'2020-05-10 20:07', '2020-05-11 20:03', '2020-05-8 20:02',
'2020-05-8 20:02', '2020-05-9 20:02',]
def compare_time(post_time):
date_object = datetime.strptime(post_time, "%Y-%m-%d %H:%M")
return (datetime.now() - date_object) < timedelta(days=1)
for t in x:
print(t, compare_time(t))
# 2020-05-12 20:16 True
# 2020-05-12 20:16 True
# 2020-05-10 20:11 False
# 2020-05-10 20:07 False
# 2020-05-11 20:03 False
# 2020-05-8 20:02 False
# 2020-05-8 20:02 False
# 2020-05-9 20:02 False

python get the quarterly dates from a date range

python get the quarterly dates from a date range
example :
start date = 01/04/2020
end date = 01/04/2021
Here I need to get the Quaternary dates from this date range.
Try:
start_date = "01/04/2020"
end_date = "01/04/2021"
pd.date_range(start_date, end_date, freq='Q')
DatetimeIndex(['2020-03-31', '2020-06-30', '2020-09-30', '2020-12-31'], dtype='datetime64[ns]', freq='Q-DEC')
pd.date_range(start date, end date, freq='3m').to_period('Q')
With pure Python:
import datetime
start_date_str = "01/04/2020"
end_date_str = "01/04/2021"
start_date = datetime.datetime.strptime(start_date_str, "%d/%m/%Y").date()
end_date = datetime.datetime.strptime(end_date_str, "%d/%m/%Y").date()
print(f"Quarters within {start_date_str} and {end_date_str}:")
start_of_quarter = start_date
while True:
far_future = start_of_quarter + datetime.timedelta(days=93)
start_of_next_quarter = far_future.replace(day=1)
end_of_quarter = start_of_next_quarter - datetime.timedelta(days=1)
if end_of_quarter > end_date:
break
print(f"\t{start_of_quarter:%d/%m/%Y} - {end_of_quarter:%d/%m/%Y}")
start_of_quarter = start_of_next_quarter

Joining 2 time strings

I am trying to solve a problem. where I am defining date and time as string in below mentioned format.
date1 = '2016-12-1'
time1 = '10:30 AM'
time2 = '11:30 PM'
I have another string add_time = '01:50' type of variables is string.
what I'm looking for is:
new_date_and_time = time1 + add_time
so that it returns
date1 and new_date_and_time
> 2016-12-1, 12:20 PM (10:30 AM + 1:50)
but if I am adding time2 + add_time the date is also changed,
so it should print 2016-12-2, 1:20 AM
Is there any package which can do this?
Convert strings to datetime object, then add time using timedelta
from datetime import datetime, timedelta
date1 = '2016-12-1'
time1 = '10:30 AM'
date_object = datetime.strptime(date1 + ' ' + time1, '%Y-%m-%d %I:%M %p')
new_date_object = date_object + timedelta(hours=1) + timedelta(minutes=50)

How to get the data in a given time period

I try to do the following query to give me the tournaments in this period:
sart_date = 2014-05-01 00:00:00
end_date = 2014-05-31 23:59:59
Here is the code I use for this purpose:
start_date = datetime.datetime.strptime(request.GET['start_date'], '%Y-%m-%d %H:%M:%S')
end_date = datetime.datetime.strptime(request.GET['end_date'], '%Y-%m-%d %H:%M:%S')
upcoming = Tournament.objects.filter(Q(started__gte=start_date), Q(ended__lte=end_date),
Q(championship_id=championship_id))
print upcoming.query
When you print an application I get the following condition:
.....WHERE (`tournaments_tournament`.`started` >= 2014-04-30 21:00:00 AND `tournaments_tournament`.`ended` <= 2014-05-31 20:59:59 AND `tournaments_tournament`.`championship_id` = 11 )....
Here is how the fields appear in the model:
started = models.DateTimeField (_('start date and time'))
ended = models.DateTimeField (_('end date and time'), null = True, blank=True)
Does anyone have any idea why so obtained and there is a way to fix this?

Categories