How to use parser on multiple time objects - python

I have an list:
list = ['2022-06-01', '2022-02-02']
Now am using parser to convert this to python date object. like this,
from dateutil import parser
def to_date(value):
for data in value:
return parser.parse(data)
Above one gives just one output, but i need the output for both the times and also need to convert that to an string like this:
From : June 1, 2022 | To: Feb. 28, 2022
Is that possible with parser ?

You only get one value back from your to_date function because you exit the function in the first loop iteration. You need to introduce an list storing your parsed dates temporary:
from dateutil import parser
def to_date(date_list):
parsed_date_list = []
for date in date_list:
parsed_date_list.append(parser.parse(date))
return parsed_date_list
date_list = ['2022-06-01', '2022-02-02']
res = to_date(date_list)
Or using a list comprehension to keep your code more concise:
from dateutil import parser
def to_date(date_list):
return [parser.parse(date) for date in date_list]
date_list = ['2022-06-01', '2022-02-02']
res = to_date(date_list)
And to format your string, simply use the strftime function as pointed out by kpie
in his comment:
# res = to_date(date_list)
date_format = "%b %d, %Y"
print(f"From: {res[0].strftime(date_format)} | To: {res[1].strftime(date_format)}")
Do not use list as a variable name. list is a data structure and therefore already in use by the class list.

You can use the standard datetime library to perform the parsing.
datetime.datetime.strptime allows you to convert a datetime string to a datetime object.
datetime.datetime.strftime allows you to convert a datetime object to the desired string.
dt_from, dt_to = [datetime.datetime.strptime(x, "%Y-%m-%d") for x in dt_list]
dt_str = f"From : {datetime.datetime.strftime('%b %d,%Y', dt_from)} | To: {datetime.datetime.strftime('%b %d,%Y', dt_to)}"]

Related

Split URL at - With Python

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 to change Day/Month/Year format to Month/Day/Year in Python

I have a column that the date is in Day/Month/Year format and it is stored in object format. How can I change it to Month/Day/Year format in python?
Here is an example: How can I change 13/3/2021 to 3/13/2021?
Simple solution is using split:
def convert_format1(s: str):
d, m, y = s.split("/")
return "/".join((m, d, y))
Or you can use datetime module to convert string to datetime object(.strptime) and vice versa(.strftime):
from datetime import datetime
def convert_format2(s: str):
source_format = "%d/%m/%Y"
destination_format = "%m/%d/%Y"
d = datetime.strptime(s, source_format)
return d.strftime(destination_format)
You can then apply these functions to your dataframe's column.
note: AFAIK .strftime() method adds zero padding to the string representation of day and month. If you don't want this behavior you have to strip it manually after that.
note: second function is safer since it checks the dates to be valid as well.
import datetime
t = datetime.date.today()
print(t.month,t.day,t.year,sep="/")
change the value inside the print should let you set yourself

Convert string to timestamp python

I'm trying to convert the list of str to the list of timestamps, then want to create the list of time delta of timestamps using total_seconds()
from datetime import datetime
a = ['091122333','092222222','093333333']
for i in a:
datetime.strptime(str(i),'%H:%M:%S.%f')
print(a)
It shows the error code of time data '091122333' does not match format '%H:%M:%S.%f'
I want to make timestamp 09(%H)11(%M)22(%S)333(%F) if possible.
Could you give me the advice above?
Thank you very much...
You have to first change the representation ( You have : which is not present in list of string in a) and how You manage what is returned from datetime.strptime (You have to store the value while You iterate through list) like that:
from datetime import datetime
a = ['091122333','092222222','093333333']
for t in range(len(a)):
a[t] = datetime.strptime(a[t],'%H%M%S%f')
delta = a[1]-a[0]
print(delta.total_seconds())
The format passed to strptime should represent the format used in the string (there are no colons in your string):
from datetime import datetime
a = ['091122333', '092222222', '093333333']
for i in a:
dt = datetime.strptime(str(i), '%H%M%S%f')
print(dt)
Out:
1900-01-01 09:11:22.333000
1900-01-01 09:22:22.222000
1900-01-01 09:33:33.333000

How to get timedelta in seconds from a string? Example: +414 00:45:41.004000

I have data of timedeltas which looks like this:
time_delta = '+414 00:45:41.004000'
So, these values are strings and they are of the format ddd hh:mm:ss.f. I now want to get this deltas to seconds. I tried to use .total_seconds() but it did not work.
How could I achieve what I am trying to do?
If you always assume the same input format, you can build a function as below (result to be checked with a simple case) :
import datetime as dt
def parseTimeDelta(time_delta_str):
splitted = time_delta_str.split(' ')
day_part = int(splitted[0][1:])
time_part = dt.datetime.strptime(splitted[1], "%H:%M:%S.%f")
delta = dt.timedelta(days=day_part, hours=time_part.hour, minutes=time_part.minute, seconds=time_part.second,microseconds=time_part.microsecond)
return delta.total_seconds()
time_delta = '+414 00:45:41.004000'
parseTimeDelta(time_delta)
can do this with pandas library
import pandas as pd
# Create the Timedelta object
td = pd.Timedelta('3 days 06:05:01.000000111')
print(td)
print(td.seconds)
Unfortunately we can't create a timedelta with a formatted string directly, but we can get a similar effect with regex then unpack parsed values into a timedelta.
import re
import datetime
# Create parser for your time format with named groups that match timedelta kwargs
time_parser = re.compile(r"\+(?P<days>\d+)\s+(?P<hours>\d{2}):(?P<minutes>\d{2}):(?P<seconds>\d{2})\.(?P<microseconds>\d+)")
# Get the values from your example string
regex_match = time_parser.match("+414 00:45:41.004000")
time_dict = regex_match.groupdict()
# Convert the time values to integers from strings
timedelta_kwargs = {k: int(v) for k, v in time_dict.items()}
# Make a time delta object
delta = datetime.timedelta(**timedelta_kwargs)
# Get total seconds
delta_in_seconds = delta.total_seconds()
Organise that into some functions and you'll get the functionality you're looking for with standard python packages.

problem of date conversion from english to french

I try to convert a date in english (2019-10-07) in french (07/10/2016)
I try
dat = '07/10/2019'
dat = time.strftime('%Y-%m-%d')
but got the result '2019-10-16' instead of '2019-10-07'
using datetime you can decide the format in which the source date is provided, and the target format you want.
from datetime import datetime
dat = '07/10/2019'
datetime.strptime(dat, "%d/%m/%Y").strftime("%Y-%m-%d")
out[6]: '2019-10-07'
strftime needs a time/date to convert, and it will use the current date and time if you don't provide one. The previous value of dat is not relevant - this information is not seen by strftime.
You need to provide the time information that strftime will format, as a tuple that you can get by parsing the original string. For this, use strptime (f for format, p for parse).
So:
dmy = '07/10/2019'
ymd = time.strftime('%Y-%m-%d', time.strptime(dmy, '%d/%m/%Y'))
# ^^^^^^^^ ^^^^^^^^
# output schema input schema
# now ymd is '2019-10-07'
(Or you can use the datetime module as in the other answer. This way, the parsing gives you an object, which has a method to format back - so you can write the whole operation "in order" on the line. But the general principle is the same: you need to parse, then format, and you need to specify the schema on each side.)
with :
dat = time.strftime('%Y-%m-%d')
you recover your actual date.
you need to make :
from datetime import datetime
dat = '07/10/2019'
dat = datetime.strptime(dat, '%m/%d/%Y')
print(dat.strftime('%Y-%m-%d') )

Categories

Resources