I have files which contain the full date and time in its name. I want to extract the particular format and print that as my first line of CSV I am writing.
My file name is like below:
VIN5_2019-04-03_10-21-26_38
I want the first line of my CSV to print as below:
date Wed Apr 3 10:21:26.000 am 2019
My code is below:
import can
import csv
import datetime
import re
filename = open('C:\\Users\\xyz\\files\\time_linear_Hexa.csv', "w")
log1 = can.BLFReader('C:\\Users\\xyz\\blf files\\VIN5_2019-04-03_10-33-59_39.blf')
filename.write(re.search("([0-9]{4}\-[0-9]{2}\-[0-9]{2})", filename))
filename.write('base hex timestamps absolute\ninternal events logged \n// version 11.0.0 \n')
How can I achieve date and time in the same format as the file image like shown in the screenshot below?
Using regex and datetime module.
Ex:
import re
import datetime
s = "VIN5_2019-04-03_10-21-26_38"
m = re.search(r"[A-Z]+\d_(?P<date>\d{4}\-\d{2}\-\d{2})_(?P<time>\d{2}\-\d{2}\-\d{2})", s)
if m:
print(datetime.datetime.strptime("{} {}".format(m.group('date'), m.group('time')), "%Y-%m-%d %H-%M-%S").strftime("%a %b %d %H:%M:%S.%f %p %Y"))
Output:
Wed Apr 03 10:21:26.000000 AM 2019
You can use a lookahead and loosbehind to extract the datetime string, use strptime to convert it to a datetime object and then use strftime to formate it to the desired form.
import re
import datetime from datetime
s = "VIN5_2019-04-03_10-21-26_38"
res = re.search('(?<=\w{5})[\w-]*(?=_\d{2})', s)
dt_string = res[0]
dt = datetime.strptime(dt_string, '%Y-%m-%d_%H-%M-%S')
'{} {} {}'.format(dt.strftime('%a %b %d %H:%M:%S.%f')[:-3], dt.strftime('%p').lower(), dt.strftime('%Y'))
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")
I have data with the date format as follows:
date_format = 190410
year = 19
month = 04
date = 10
I want to change the date format, to be like this:
date_format = 10-04-2019
How do I solve this problem?
>>> import datetime
>>> date = 190410
>>> datetime.datetime.strptime(str(date), "%y%m%d").strftime("%d-%m-%Y")
'10-04-2019'
datetime.strptime() takes a data string and a format, and turns that into datetime object, and datetime objects have a method called strftime that turns datetime objects to string with given format. You can look what %y %m %d %Y are from here.
This is what you want(Notice that you have to change your format)
import datetime
date_format = '2019-04-10'
date_time_obj = datetime.datetime.strptime(date_format, '%Y-%m-%d')
print(date_time_obj)
Here is an other example
import datetime
date_time_str = '2018-06-29 08:15:27.243860'
date_time_obj = datetime.datetime.strptime(date_time_str, '%Y-%m-%d %H:%M:%S.%f')
print('Date:', date_time_obj.date())
print('Time:', date_time_obj.time())
print('Date-time:', date_time_obj)
You can also do this
from datetime import datetime, timedelta
s = "20120213"
# you could also import date instead of datetime and use that.
date = datetime(year=int(s[0:4]), month=int(s[4:6]), day=int(s[6:8]))
print(date)
There are many ways to achieve what you want.
I have a file (based on a class project) of scraped Tweets. At this point lines in the file look like:
#soandso something something Permalink 1:40 PM - 17 Feb 2016<br><br>
#soandso something something Permalink 1:32 PM - 16 Feb 2016<br><br>
I'm trying to sort the lines in the file by date. This is what I've cobbled together so far.
import re
from datetime import datetime
when = re.compile(r".+</a>(.+)<br><br>")
with open('tweets.txt','r+') as outfile:
sortme = outfile.read()
for match in re.finditer(when, sortme):
tweet = match.group(0)
when = match.group(1)
when = datetime.strptime(when, " %I:%M %p - %d %b %Y")
print when
Which will print out all the dates in the lines having converted the format
from 1:40 PM - 17 Feb 2016 to 2016-02-17 13:40:00, which I believe is a datetime. I have searched high and low over the last few days for clues about how I'd then sort all the lines in the file by datetime. Thanks for your help!
I have searched high and low over the last few days for clues about how I'd then sort all the lines in the file by datetime.
def get_time(line):
match = re.search(r"</a>\s*(.+?)\s*<br><br>", line)
if match:
return datetime.strptime(match.group(1), "%I:%M %p - %d %b %Y")
return datetime.min
lines.sort(key=get_time)
It assumes that the time is monotonous in the given time period (e.g., no DST transitions) otherwise you should convert the input time to UTC (or POSIX timestamp) first.
It seems you have already solved the regex problem... so to convert your datetime into a measurable quantity convert to seconds like so:
import time
time.mktime(when.timetuple())
then for sorting you can make a lot off different routes. the simplest example is:
import operator
s = [("ab",50),("cd",100),("ef",15)]
print sorted(s,key=operator.itemgetter(1))
## [('ef', 15), ('ab', 50), ('cd', 100)]
This question already has answers here:
Convert string "Jun 1 2005 1:33PM" into datetime
(26 answers)
Closed 8 years ago.
I need to convert date string "Dec 17 00:00:06" to string "2014-12-17 00:00:06" in python. I looked at the datetime.strptime but still can't find a way for this.
eg:
Dec 17 00:00:06 to 2014-12-17 00:00:06
You can use datetime module.
For e.g.
>>> import datetime
>>> do = datetime.datetime.strptime("Dec 17 2014 00:00:06", "%b %d %Y %H:%M:%S")
>>> do.strftime("%Y-%m-%d %H:%M:%S")
'2014-12-17 00:00:06'
We can replace year value to 2014 like following:
>>> do = datetime.datetime.strptime("Dec 17 00:00:06", "%b %d %H:%M:%S")
>>> do.strftime("%Y-%m-%d %H:%M:%S")
'1900-12-17 00:00:06'
>>> do1 = do.replace(year=2014)
>>> do1.strftime("%Y-%m-%d %H:%M:%S")
'2014-12-17 00:00:06'
If we want only time value then we can try like-
>>> do = datetime.datetime.strptime("Dec 17 00:00:06", "%b %d %H:%M:%S")
>>> do.strftime("%H:%M:%S")
'00:00:06'
Updated: update datetime string from file with its time string.
Algo:
Get content from the input text file.
Used re module i.e regular expression to get all pattern from content.
Use set method to remove duplicate values.
Convert datetime string to time string and update content.
Write new content into same file or other file.
code is:-
import datetime
import re
p = "/home/vivek/Desktop/input.txt"
with open(p, "rb") as fp:
content = fp.read()
date_values = set(re.findall("\[([^]]+)\]", content))
for i in date_values:
do = datetime.datetime.strptime(i, "%b %d %H:%M:%S")
content = content.replace("[%s]"%i, "%s"%(do.strftime("%H:%M:%S")) )
p = "/home/vivek/Desktop/output.txt"
with open(p, "wb") as fp:
fp.write(content)
Using datetime module will help you out.
from datetime import datetime
Firstly convert your date string to a datetime object by writing the line below.
date_obj = datetime.strptime("Dec 17 2014 00:00:06", "%b %d %Y %H:%M:%S")
Then convert that date object to a string.
date_obj.strftime("%Y-%m-%d %H:%M:%S")
You can change the parameters of the above strftime() function, and get different formats as per your requirments. Please follow python datetime
Here is the link to the options for the parameters which can be passed in the strftime() function parameter options
Go and play around as per your requirement.
from dateutil import parser
parser.parse('Dec 17 00:00:06').isoformat()
>>> '2015-12-17T00:00:06'
I am trying to write a program that asks for the user to input the date in the format mm/dd/yyyy and convert it. So, if the user input 01/01/2009, the program should display January 01, 2009. This is my program so far. I managed to convert the month, but the other elements have a bracket around them so it displays January [01] [2009].
date=input('Enter a date(mm/dd/yyy)')
replace=date.replace('/',' ')
convert=replace.split()
day=convert[1:2]
year=convert[2:4]
for ch in convert:
if ch[:2]=='01':
print('January ',day,year )
Thank you in advance!
Don't reinvent the wheel and use a combination of strptime() and strftime() from datetime module which is a part of python standard library (docs):
>>> from datetime import datetime
>>> date_input = input('Enter a date(mm/dd/yyyy): ')
Enter a date(mm/dd/yyyy): 11/01/2013
>>> date_object = datetime.strptime(date_input, '%m/%d/%Y')
>>> print(date_object.strftime('%B %d, %Y'))
November 01, 2013
You might want to look into python's datetime library which will take care of interpreting dates for you. https://docs.python.org/2/library/datetime.html#module-datetime
from datetime import datetime
d = input('Enter a date(mm/dd/yyy)')
# now convert the string into datetime object given the pattern
d = datetime.strptime(d, "%m/%d/%Y")
# print the datetime in any format you wish.
print d.strftime("%B %d, %Y")
You can check what %m, %d and other identifiers stand for here: https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior
As a suggestion use dateutil, which infers the format by itself:
>>> from dateutil.parser import parse
>>> parse('01/05/2009').strftime('%B %d, %Y')
'January 05, 2009'
>>> parse('2009-JAN-5').strftime('%B %d, %Y')
'January 05, 2009'
>>> parse('2009.01.05').strftime('%B %d, %Y')
'January 05, 2009'
Split it by the slashes
convert = replace.split('/')
and then create a dictionary of the months:
months = {1:"January",etc...}
and then to display it do:
print months[convert[0]] + day + year