How to convert the string to date time format? - python

I have the following string 20211208_104755, representing date_time format. I want to convert it to the python datetime format using datetime.strip() method.
mydatetime = "20211208_104755"
datetime_object = datetime.strptime(mydatetime, '%y/%m/%d')
However I am getting the following error.
ValueError: time data '20211208' does not match format '%y/%m/%d'

The second argument in strptime has to match the pattern of your datetime string. You can find the patterns and their meaning on https://docs.python.org/3/library/datetime.html
In your case, you can format it as
from datetime import datetime
mydatetime = "20211208_104755"
datetime_object = datetime.strptime(mydatetime, '%Y%m%d_%H%M%S')
print(datetime_object)
>>> 2021-12-08 10:47:55

what should work is to define how the mydatetime string is composed.
example:
%Y is the year (4 digits); check here for format (section strftime() Date Format Codes)
So in your example I would assume it's like this:
mydatetime = "20211208_104755"
datetime_object = datetime.strptime(mydatetime, '%Y%m%d_%H%M%S')
print (datetime_object)
result
2021-12-08 10:47:55
and
type(datetime_object)
datetime.datetime

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")

Get YYYY-DD-MM from YYYY-DD-MM HH:MM:SS

I have a date in the format 2012-01-01 06:00:00. I want to get only the date in the format 2012-01-01.
I've tried multiple links such as Converting (YYYY-MM-DD-HH:MM:SS) date time
But, I could not find the solution.
Parse. str -> date.
from datetime import datetime
s = "2012-01-01 06:00:00"
dt = datetime.strptime(s, "%Y-%m-%d %H:%M:%S")
Format. date -> str.
s_ymd = dt.strftime("%Y-%m-%d")
Result:
>>> s_ymd
'2012-01-01'
Assuming your date is a string, the following works fine:
str = "2012-01-01 06:00:00"
print(str[:10])
The notation [:10] basically means "take first 10 characters of the string".

string convert to date time in python

I have a list of date time strings like this.
16-Aug-2019
I want to convert the string to 2019-08-01 this date format, and I have tried on this code , but it's getting me an error.
formatd_date = datetime.strptime(formatd_date, '%y-%m-%d')
ValueError: time data 'As-of' does not match format '%y-%m-%d'
If any can help, it will be huge thank.
Convert to datetime format and then convert to string format you want to:
>>> from datetime import datetime
>>> a = "16-Aug-2019"
>>> datetime.strptime(a, "%d-%b-%Y").strftime("%Y-%m-%d")
'2019-08-16'
Documentation: https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior
Just fails because %y is 2-digit year. Use %Y for 4-digit year.

Convert Timestamp to ISO Date

I am extracting Data from Mongodb using some date filter. In mongo my date is in ISO format . As i am dynamically adding date from some variable which is in timestamp format(2019-07-15 14:54:53).Getting Empty Result
curs = col1.aggregate([{'$match':{update_col: {'$gte': last_updt }}},{'$project':json_acceptable_string}])
I am expecting Rows after filtering but acual its giving empty dataset
you can use datetime.strptime to parse the original string to a datetime object, then use datetime.isoformat to get it in ISO format.
try this:
import datetime
original_date = '2019-07-15 14:54:53'
date_obj = datetime.datetime.strptime(original_date, "%Y-%m-%d %H:%M:%S")
iso_date = date_obj.isoformat()
print(iso_date)
try this
from dateutil import parser as date_parser
dt_obj = date_parser.parse('2019-07-15 14:54:53')
where dt_obj is an object of standard datetime.datetime class
You can use fromisoformat.
Try
from datetime import datetime
iso_string = '2019-07-15 14:54:53'
you_date_obj = datetime.fromisoformat(iso_string)

Create a datetime from a string representation in a CSV file

I have a CSV file with recorded datetimes with a particular format:
%Y-%m-%d %H:%M:%s %Z
Example:
2017-02-11 14:11:42 PST
I am trying to format the datetime to a friendlier value to use later on.
However, I have been unable to create a datetime object with my code so far.
Here is my code:
for r in row:
purchase_date.append(
datetime.strptime(row['purchase-date'], "%Y/%m/%d %H:%M:%S %Z")
)
This is the error received:
ValueError: time data '2017-02-11 14:11:42 PST' does not match format %Y/%m/%d %H:%M:%S %Z'
Timezones are often rather wonky when trying to convert from a string. It is often best to deal with the timezone string yourself. Here is a bit of code which separates the timezone from the timestamp, and then converts them separately.
Code:
import datetime as dt
import pytz
my_timezones = dict(
PST='US/Pacific',
)
def convert_my_datetime_str(dt_str):
# split into time and timezone
timestamp, tz_str = dt_str.rsplit(' ', 1)
# convert the date string to datetime
time = dt.datetime.strptime(timestamp, "%Y-%m-%d %H:%M:%S")
# get a timezone name
tz = pytz.timezone(my_timezones[tz_str])
# return a timezone aware datetime
return tz.localize(time)
Test Code:
print(convert_my_datetime_str('2017-02-11 14:11:42 PST'))
Results;
2017-02-11 14:11:42-08:00
You should be able to just change the format to match your date strings. In the error, your date string has dashes instead of slashes, so make the format string match:
for r in row:
purchase_date.append(
datetime.strptime(row['purchase-date'], "%Y-%m-%d %H:%M:%S %Z")
)

Categories

Resources