I'm trying to open a text file with a dynamic path. How could I make it work something like this?:
f = open("date/month/week.txt","a")
date, month, and week are the current date, month, and week.
You can use str.format:
f = open("{}/{}/{}.txt".format(date, month, week),"a")
I suggest you finish the Python tutorial before trying anything too ambitious!
Use the datetime module with strftime formatting.
import datetime
f = open(datetime.datetime.strftime(datetime.datetime.now(), '%d/%m/%U') + '.txt', 'a')
For a date of June 8, 2015, this creates a filename of 08/06/23.txt.
you can try this. using string format and datetime for a complete solution
d = datetime.datetime.today()
date = d.date()
month = d.month
week = d.isocalendar()[1]
f = open('{date}/{month}/{week}.txt'.format(date=date, month=month, week=week),"a")
my personal preference on the naming convention for dates and a file would be in the format 'yyyy-mm-dd' you can include the week on this too, which would look like this
d = datetime.datetime.today()
date = d.date()
week = d.isocalendar()[1]
f = open('{date}-{week}.txt'.format(date=date, week=week),"a")
that would result in a file of this format. 2015-06-08-24.txt
Related
Does anyone know how I can extract the end 6 characters in a absoloute URL e.g
/es/ideas-de-trading-y-noticias/el-ibex-35-insiste-en-buscar-los-7900-puntos-a-la-espera-de-las--221104
This is not a typical URL sometimetimes it ends -221104
Also, is there a way to turn 221104 into the date 04 11 2022 easily?
Thanks in advance
Mark
You should use the datetime module for parsing strings into datetimes, like so.
from datetime import datetime
url = 'https://www.ig.com/es/ideas-de-trading-y-noticias/el-ibex-35-insiste-en-buscar-los-7900-puntos-a-la-espera-de-las--221104'
datetime_string = url.split('--')[1]
date = datetime.strptime(datetime_string, '%y%m%d')
print(f"{date.day} {date.month} {date.year}")
the %y%m%d text tells the strptime method that the string of '221104' is formatted in the way that the first two letters are the year, the next two are the month, and the final two are the day.
Here is a link to the documentation on using this method:
https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior
If the url always has this structure (that is it has the date at the end after a -- and only has -- once), you can get the date with:
str_date = str(url).split("--")[1]
Relaxing the assumption to have only one --, we can have the code working by just taking the last element of the splitted list (again assuming the date is always at the end):
str_date = str(url).split("--")[-1]
(Thanks to #The Myth for pointing that out)
To convert the obtained date into a datetime.date object and get it in the format you want:
from datetime import datetime
datetime_date = datetime.strptime(str_date, "%y%m%d")
formatted_date = datetime_date.strftime("%d %m %Y")
print(formatted_date) # 04 11 2022
Docs:
strftime
strptime
behaviour of the above two functions and format codes
Taking into consideration the date is constant in the format yy-mm-dd. You can split the URL by:
url = "https://www.ig.com/es/ideas-de-trading-y-noticias/el-ibex-35-insiste-en-buscar-los-7900-puntos-a-la-espera-de-las--221104"
time = url[-6:] # Gets last 6 values
To convert yy-mm-dd into dd mm yy we will use the DateTime module:
import datetime as dt
new_time = dt.datetime.strptime(time, '%y%m%d') # Converts your date into datetime using the format
format_time = dt.datetime.strftime(new_time, '%d-%m-%Y') # Format
print(format_time)
The whole code looks like this:
url = "https://www.ig.com/es/ideas-de-trading-y-noticias/el-ibex-35-insiste-en-buscar-los-7900-puntos-a-la-espera-de-las--221104"
time = url[-6:] # Gets last 6 values
import datetime as dt
new_time = dt.datetime.strptime(time, '%y%m%d') # Converts your date into datetime using the format
format_time = dt.datetime.strftime(new_time, '%d %m %Y') # Format
print(format_time)
Learn more about datetime
You can use python built-in split function.
date = url.split("--")[1]
It gives us 221104
then you can modify the string by rearranging it
date_string = f"{date[4:6]} {date[2:4]} {date[0:2]}"
this gives us 04 11 22
Assuming that -- will only be there as it is in the url you posted, you can do something as follows:
You can split the URL at -- & extract the element
a = 'https://www.ig.com/es/ideas-de-trading-y-noticias/el-ibex-35-insiste-en-buscar-los-7900-puntos-a-la-espera-de-las--221104'
desired_value = a.split('--')[1]
& to convert:
from datetime import datetime
converted_date = datetime.strptime(desired_value , "%y%m%d")
formatted_date = datetime.strftime(converted_date, "%d %m %Y")
how do i convert a date: 2022-09-28 to 28092022 in python?
I have some files that have this date pattern in their name and I need to convert this date to find the latest one, is possible?
Every help is welcome :)
So, when you use date.today() you get back a datetime.date object:
>>> from datetime import date
>>> date.today()
datetime.date(2022, 9, 28)
On this, you can directly use the .strftime() method to get back a string with whatever format you would like:
>>> date.today().strftime('%d%m%Y')
'28092022'
You can use this function:
def getDateString(date):
year, month, day = str(date).split("-")
return day+month+year
Eg:
date = datetime(year=2022, month=9, day = 28).date()
print(getDateString(date)) // returns '28092022'
we can use regex to get the task done:
the first step should be to get the date expression from the file name.
(if there is more than one file name to read and modify, we can run the task in a loop).
extract the date expression from the file name:
import re
file_name = 'backup 2022-09-28-17:33.xyz' # a sample file name
pattern = r'(\d{4}-\d{2}-\d{2})'
date = ''.join(re.findall(pattern, file_name)).split('-')
result of date: ['2022', '09', '28']
in the second step we replace the current date expression by the new ones:
file_name = re.sub(pattern, ''.join(date[::-1]), file_name)
print(file_name)
result: backup 28092022-17:33.xyz
Using todays date, I would like to reformat the date so that it reads as follows:
25-09-2021
So far I have come up with a very clumsy way of doing:
from datetime import datetime, timedelta, date
print(datetime.now())
the_date = datetime.strftime(datetime.now(), '%Y-%m-%d')
print(the_date)
a = the_date[-2:]
print(a)
b = the_date[5:-3]
print(b)
c = the_date[:4]
print(c)
new_date = str(a)+'-'+str(b)+'-'+str(c)
print(new_date)
Surely there is a cleaner way of doing this?
You could simply specify the formula differently:
datetime.strftime(datetime.now(), '%d-%m-%Y')
It is not clear what type of data you are starting with. If you have an existing date string in the format YYYY-MM-DD, you can split and reorder it.
Here's an example.
date = '2021-09-25'
Y, M, D = date.split('-')
date = f"{D}-{M}-{Y}"
print(date) # Prints 25-09-2021
Assuming you start with a string with the given format
original_date_str = datetime.now().strftime('%Y-%m-%d')
#this line recreates a datetime object from the string
original_date_datetime = datetime.strptime(original_date_str, '%Y-%m-%d')
#this value will be a string with the new format
new_fmt_date_str = original_date_datetime.strftime("%d-%m-%Y")
I haven't tested the code yet, but pending some silly mistake it should work.
I'm using tkcalendar to get dates. The date format is 'DD/MM/YYYY'. However, SQL DATE format accepts only 'YYYY-MM-DD'.
I have the following code:
dated = cal.get_date()
dates = dated.split('/')
reverse_dates = dates[::-1]
separator = '-'
final_date = separator.join(reverse_dates)
print(final_date)
where, cal is a tkcalendar.Calendar object. Is there a shorter way to write this code?
Try using strftime:
date = cal.get_date()
date_str = date.strftime("%Y-%m-%d")
print("date formatted: ", date_str)
Using a value of datetime.now() for the starting date, the output from the above script is:
date formatted: 2020-11-23
I want to convert a string like this "29-Apr-2013-15:59:02"
into something more usable.
The dashes can be easily replaced with spaces or other characters. This format would be ideal: "YYYYMMDD HH:mm:ss (20130429 15:59:02)".
Edit:
Sorry, I did not specifically see the answer in another post. But again, I'm ignorant so could have been looking at the solution and didn't know it. I've got this working, but I wouldn't consider it "pretty."
#29-Apr-2013-15:59:02
import sys, datetime, time
#inDate = sys.argv[1]
inDate = 29-Apr-2013-15:59:02
def getMonth(month):
monthDict = {'Jan':'01','Feb':'02','Mar':'03','Apr':'04','May':'05','Jun':'06','Jul':'07','Aug':'08','Sep':'09','Oct':'10','Nov':'11','Dec':'12'}
for k, v in monthDict.iteritems():
if month == k:
return v
day = inDate[:2]
#print day
month = inDate[3:6]
#print month
year = inDate[7:11]
#print year
time = inDate[-8:]
#print time
newDate = year+getMonth(month)+day
newDateTime = newDate+" "+time
print newDate
print newDateTime
Any thoughts on improving?
Use datetime.strptime() to parse the inDate string into a date object, use datetime.strftime() to output in whatever format you like:
>>> from datetime import datetime
>>> inDate = "29-Apr-2013-15:59:02"
>>> d = datetime.strptime(inDate, "%d-%b-%Y-%H:%M:%S")
>>> d
datetime.datetime(2013, 4, 29, 15, 59, 2)
>>> d.strftime("YYYYMMDD HH:mm:ss (%Y%m%d %H:%M:%S)")
'YYYYMMDD HH:mm:ss (20130429 15:59:02)'
Have you investigated dateutil?
http://labix.org/python-dateutil
I found a similar question to yours:
How do I translate a ISO 8601 datetime string into a Python datetime object?
You want to look into datetime, in particular strptime.