How to format string time object with python? - python

I am using django python. Now I want to convert the following timing string into hours, minutes ,am/pm format.
string_time = '2022-09-13 11:00:00.996795+00'
expected output:
11:00 am
actual output is :
ValueError: time data '2022-09-13 11:00:00.996795+00' does not match format '%m/%d/%y %H:%M:%S'
my code :
def time_slots(self,string_time='2022-09-13 11:00:00.996795+00'):
print(datetime.strptime(string_time, '%m/%d/%y %H:%M:%S'),type(start_time))
start_time = datetime.strptime(string_time, '%m/%d/%y %H:%M:%S')
return formated_start_time

When you remove the last three chars ('+00') and replace the space with T you can use datetime.datetime.fromisoformat(str) to get a datetime object.
from datetime import datetime
timestr = '2022-09-13 11:00:00.996795+00'
timestr = timestr.rstrip(timestr[-3:]).replace(' ', 'T')
date = datetime.fromisoformat(timestr)
from there you can use date.hour and date.minute to get the values you want.
e.g.:
hour = date.hour%12
minute = date.minute
addition = ''
if date.hour > 12:
addition = 'pm'
else:
addition = 'am'
print(f'{hour}:{minute} {addition}')

I'm not sure if the last string +00 is useful.
If not, the following implementation can help you.
from datetime import datetime
def time_slots(string_time='2022-09-13 11:00:00.996795+00'):
date = datetime.strptime(string_time[:-3], '%Y-%m-%d %H:%M:%S.%f')
return date.strftime("%H:%M %p")
output = time_slots()
print(output) # the output is: 11:00 AM

You can use the parse function provided by dateutil:
from dateutil import parse
string_time = '2022-09-13 11:00:00.996795+00'
dt = parse(string_time)
return dt.strftime("%H:%M %p")
Result: 11:00 AM

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

Reformat datetime object to use slashes instead of dashes

I'm trying to normalize a date string: '6-3-1975' to a datetime object in this format: '06/03/1975'
I have this method:
def normalizeDate(date):
formatted_date = date.replace('-', '/')
date_obj = datetime.strptime(formatted_date, '%m/%d/%Y').date()
# date = datetime.strftime(date_obj, '%m/%d/%Y')
# print(date)
return date_obj
When printing out .date() the format uses dashes, I also tried using strftime but that would convert the date_object back into a string. Is there a way to reformat the date to use slashes and still be a datetime object?
You can process the date string yourself, to give it the desired format and then convert it to datetime object:
def normalizeDate(date):
newDate = '/'.join(str.zfill(elem,2) for elem in date.split('-'))
date_obj = datetime.strptime(newDate, '%m/%d/%Y').date()
return date_obj
In order to print your date to that specific format, you will have to use strftime to the new datetime object created:
inDate = '6-3-1975'
d = normalizeDate(inDate)
print(d.strftime('%m/%d/%Y'))
print(type(d))
This is the only way to set the format of a datetime object.

How to fix date formatting using python3

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.

How to convert timestamp into string in Python

I have a problem with the following code. I get an error "strptime() argument 1 must be str, not Timestamp"
I guess that what I should do is to convert date from timestamp to string but I do not know what to do.
class TweetAnalyzer:
def tweets_to_data_frame(self,ElonMuskTweets):
df = pd.DataFrame(data=[tweet.text for tweet in ElonMuskTweets],columns=['Tweets'])
df['Text length'] = np.array ([len(tweet.text)for tweet in ElonMuskTweets])
df['Date and time of creation'] = np.array ([tweet.created_at for tweet in ElonMuskTweets])
df['Likes'] = np.array ([tweet.favorite_count for tweet in ElonMuskTweets])
df['Retweets'] = np.array ([tweet.retweet_count for tweet in ElonMuskTweets])
list_of_dates = []
list_of_times = []
for date in df['Date and time of creation']:
date_time_obj = datetime.strptime(date, '%Y-%m-%d %H:%M:%S')
list_of_dates.append(date_time_obj.date())
list_of_times.append(date_time_obj.time())
df['Date'] = list_of_dates
df['Time'] = list_of_times
df['Date'] = pd.to_datetime(df['Date'])
start_date = '2018-04-13'
end_date = '2019-04-13'
mask1 = (df['Date'] >= start_date) & (df['Date'] <= end_date)
MuskTweets18_19 = df.loc[mask1]
return MuskTweets18_19.to_csv ('elonmusk_tweets.csv',index=False)
I get the error in
date_time_obj = datetime.strptime(date, '%Y-%m-%d %H:%M:%S')
How can I solve this prolem?
Thank you in advance
Can you coerce the data type to a string to perform this calculation?
date_time_obj = datetime.strptime(str(date), '%Y-%m-%d %H:%M:%S')
If it says "strptime() argument 1 must be str, not Timestamp", likely that you already have the pandas.Timestamp object, i.e., it is not a string but a parsed date time, only it is in Pandas' format, not Python's. So to convert, use this:
date_time_obj = date.to_pydatetime()
instead of date_time_obj = datetime.strptime(date, '%Y-%m-%d %H:%M:%S')
If the object is a Python Timestamp, you can implement:
timestamp = Timestamp('2017-11-12 00:00:00')
str_timestamp = str(timestamp)
import pandas as pd
import datetime
base = pd.to_datetime("2022-10-10")
date_list = [datetime.datetime.strftime(pd.to_datetime(base - datetime.timedelta(days=x)),"%Y-%m-%d") for x in range(7)]
print(date_list)
output will be
['2022-10-10',
'2022-10-09',
'2022-10-08',
'2022-10-07',
'2022-10-06',
'2022-10-05',
'2022-10-04']
Just adding to the above answers as ran into the following probem using the solutions provided:
AttributeError: module 'datetime' has no attribute 'strptime'
Based on the answer found here, you need to either coerce the timestamp into a string like this:
date_time_obj = datetime.datetime.strptime(str(date), '%Y-%m-%d %H:%M:%S')
Or make sure to import the class and not just the module like this:
from datetime import datetime

How do i check if timezone is present in a unicode string using Python

I am having timestamp fields in my JSON data where some of the timestamps have timestamp in this format str("2014-05-12 00:00:00") and another in this format str("2015-01-20 08:28:16 UTC"). I would like to get year, month, day fields only from the string. I have tried the following approach but not sure what is the problem. Can someone please correct me. I have searched some of the answers from StackOverflow but nothing helped me.
from datetime import datetime
date_posted=str("2014-05-12 00:00:00")
date_posted_zone=str("2015-01-20 08:28:16 UTC")
def convert_timestamp(date_timestamp=None):
if '%Z' in date_timestamp:
d = datetime.strptime(date_timestamp, "%Y-%m-%d %H:%M:%S %Z")
else:
d = datetime.strptime(date_timestamp, "%Y-%m-%d %H:%M:%S")
return d.strftime("%Y-%m-%d")
print convert_timestamp(date_posted_zone)
I've tried following code to search timezone in str and its working.
from datetime import datetime
date_posted=str("2014-05-12 00:00:00")
date_posted_zone=str("2015-01-20 08:28:16 UTC")
zone=date_posted_zone.split(" ")
print(zone[2])
def convert_timestamp(date_timestamp=None):
if zone[2] in date_timestamp:
d = datetime.strptime(date_timestamp, "%Y-%m-%d %H:%M:%S %Z")
else:
d = datetime.strptime(date_timestamp, "%Y-%m-%d %H:%M:%S")
return d.strftime("%Y-%m-%d")
print convert_timestamp(date_posted_zone)
You're checking if the literal string %Z is in the timestamp value; only strptime (and strftime) can actually make use of the format character.
What you can do is simply try to parse the string as if it had a timezone, and if that fails, try to parse it without.
def convert_timestamp(date_timestamp=None):
try:
d = datetime.strptime(date_timestamp, "%Y-%m-%d %H:%M:%S %Z")
except ValueError:
d = datetime.strptime(date_timestamp, "%Y-%m-%d %H:%M:%S")
return d.strftime("%Y-%m-%d")
Of course, as written, you don't really need to parse the string at all; just split it on whitespace and return the first component. (Your existing code already assumes that the year/month/date matches.)
def convert_timestamp(date_timestamp):
return date_timestamp.split()[0]
from dateutil import parser
datetime_no_timezone = parser.parse("2015-01-20 08:28:16")
datetime_with_timezone = parser.parse("2015-01-20 08:28:16+02:00")
if datetime_no_timezone.tz == None:
# CODE ALWAYS GO THROUGH THIS
pass
if datetime_no_timezone.tz:
# CODE ALWAYS GO THROUGH THIS
pass

Categories

Resources