I need to add datetime in my filename as shown below:
User_Call_Detail_20210406_20210407000004.csv
where 20210406 is the (current date - 1) and 20210407000004 is the current date with timestamp and User Call Detail.csv is my filename. I want to make the filename as shown above.
Can anyone please help in achieving this as I am new in development.
You could try using a regular expression, like the one below:
^(.*)_(\d+)_(\d+)\.csv$
You could then use the re module to parse the sample string:
>>> import re
>>> regex = re.compile(r"^(.*)_(\d+)_(\d+)\.csv$")
>>> match = regex.search("User_Call_Detail_20210406_20210407000004.csv")
>>> groups = match.groups()
>>> groups
('User_Call_Detail', '20210406', '20210407000004')
import datetime
t = datetime.date.today()
y = (t - datetime.timedelta(days=1))
ts = round(datetime.datetime.now().timestamp())
print (y.strftime("%Y%m%d"),t.strftime("%Y%m%d"),ts)
Output:
20210413 20210414 1618410896
Related
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
I have time values in text as:
a="060453"
b="135309"
I want to convert the above into "HH:MM:SS" format and also get the difference in the same format.
13:53:09 - 06:04:53 = 07:49:06
Regards
I don't think your math is right but I think this is kind of what you want:
>>> import datetime
>>> print datetime.datetime.strptime("135309", "%H%M%S") - datetime.datetime.strptime("060453", "%H%M%S")
7:48:16
>>>
This should get you the timedelta you need-
from datetime import datetime
a="060453"
b="135309"
a = datetime.strptime(a,'%H%M%S')
b = datetime.strptime(b,'%H%M%S')
print(b-a)
I have a string s which contains two dates in it and I am trying to extract these two dates in order to subtract them from each other to count the number of days in between. In the end I am aiming to get a string like this: s = "o4_24d_20170708_20170801"
At the company I work we can't install additional packages so I am looking for a solution using native python. Below is what I have so far by using the datetime package which only extracts one date: How can I get both dates out of the string?
import re, datetime
s = "o4_20170708_20170801"
match = re.search('\d{4}\d{2}\d{2}', s)
date = datetime.datetime.strptime(match.group(), '%Y%m%d').date()
print date
from datetime import datetime
import re
s = "o4_20170708_20170801"
pattern = re.compile(r'(\d{8})_(\d{8})')
dates = pattern.search(s)
# dates[0] is full match, dates[1] and dates[2] are captured groups
start = datetime.strptime(dates[1], '%Y%m%d')
end = datetime.strptime(dates[2], '%Y%m%d')
difference = end - start
print(difference.days)
will print
24
then, you could do something like:
days = 'd{}_'.format(difference.days)
match_index = dates.start()
new_name = s[:match_index] + days + s[match_index:]
print(new_name)
to get
o4_d24_20170708_20170801
import re, datetime
s = "o4_20170708_20170801"
match = re.findall('\d{4}\d{2}\d{2}', s)
for a_date in match:
date = datetime.datetime.strptime(a_date, '%Y%m%d').date()
print date
This will print:
2017-07-08
2017-08-01
Your regex was working correctly at regexpal
I made a crawler using python.
But my crawler get date in this format:
s = page_ad.findAll('script')[25].text.replace('\'', '"')
s = re.search(r'\{.+\}', s, re.DOTALL).group() # get json data
s = re.sub(r'//.+\n', '', s) # replace comment
s = re.sub(r'\s+', '', s) # strip whitspace
s = re.sub(r',}', '}', s) # get rid of last , in the dict
dataLayer = json.loads(s)
print dataLayer["page"]["adDetail"]["adDate"]
2017-01-1412:28:07
I want only date without hours (2017-01-14), how get only date if not have white spaces?
use string subset:
>>> date ="2017-01-1412:28:07"
>>> datestr= date[:-8]
>>> datestr
'2017-01-14'
>>>
As this is not a standard date format, just slice the end.
st = "2017-01-1412:28:07"
res = st[:10]
print res
>>>2017-01-14
try this code:
In [2]: from datetime import datetime
In [3]: now = datetime.now()
In [4]: now.strftime('%Y-%m-%d')
Out[4]: '2017-01-24'
Update
I suggest you parse the date first into datetime object and then show the relevant information out of it.
for this a better approach would be using a library for this.
I use dateparser for this tasks, example usage:
import dateparser
date = dateparser.parse('12/12/12')
date.strftime('%Y-%m-%d')
Use datetime as follows to first convert it into a datetime object, and then format the output as required using the stftime() function:
from datetime import datetime
ad_date = dataLayer["page"]["adDetail"]["adDate"]
print datetime.strptime(ad_date, "%Y-%m-%d%H:%M:%S").strftime("%Y-%m-%d")
This will print:
2017-01-14
By using this method, it would give you the flexibility to display other items, for example adding %A to the end would give you the day of the week:
print datetime.strptime(ad_date, "%Y-%m-%d%H:%M:%S").strftime("%Y-%m-%d %A")
e.g.
2017-01-14 Saturday
This is my code - I want to convert a string into a time in Python - it sort of works:
import datetime
firstTime = ("18:08:14")
firstTime = datetime.datetime.strptime(firstTime, "%H:%M:%S")
print (firstTime)
The problem is, I get '1900-01-01 18:08:14' instead of just '18:08:14'. I know this is a fairly basic thing, but I'm new to Python and any help would be appreciated.
As my comment suggests, use a time class rather than datetime since you don't need the date part:
>>> from datetime import datetime
>>> firsttime = datetime.strptime('18:08:14','%H:%M:%S')
>>> print(firsttime)
1900-01-01 18:08:14
>>> print(firsttime.time())
18:08:14
or simply:
>>> firsttime = datetime.strptime('18:08:14','%H:%M:%S').time()
>>> print(firsttime)
18:08:14
try this..
>>> from datetime import datetime
>>> date=datetime.now()
>>> date.strftime('%H:%M:%S')
'23:55:17'
>>>
Your code seems fine. Just change strptime to strftime.
import datetime
firstTime = ("18:08:14")
firstTime = datetime.datetime.strftime(firstTime, "%H:%M:%S")
print (firstTime)
strptime takes a string and convert to datetime object.
strftime creates formatted string from given date,time,datetime object according to a specific format