I got this function below which helps me to change a date format from one to another:
def change_time_format(self, date_string, input_format, output_format):
if date_string == None:
return None
try:
date = datetime.datetime.strptime(date_string, input_format)
timestamp = calendar.timegm(date.timetuple())
new_formatted_date = datetime.datetime.fromtimestamp(timestamp).strftime(output_format)
return new_formatted_date
except Exception as E:
print E
return None
And when i'm calling it like this:
dtu.change_time_format('2017-01-01 12:34:56', '%Y-%m-%d %H:%M:%S', '%d%m%Y %H%M%S')
I'm getting the input as:'01012017 153456' which is wrong and needs to be: '01012017 123456', there is a difference of 3 hours for some reason.
I can't find how to fix it, I searched for several ways over the web and I couldn't find nothing.
From here:
return datetime.datetime.strptime(date_string, input_format).strftime(output_format)
Related
i have this piece of code:
symbol = 'PSTV'
end_point="https://api.polygon.io/v2/snapshot/locale/us/markets/stocks/tickers/"+symbol+"?apiKey=my_key"
a_json=requests.get(end_point).json()
if a_json['status'] == 'OK':
candle_open = a_json['ticker']['min']['o']
candle_close = a_json['ticker']['min']['c']
candle_high = a_json['ticker']['min']['h']
candle_low = a_json['ticker']['min']['l']
candle_ts = a_json['ticker']['lastQuote']['t']
print(candle_ts/1000000)
candle_ts = datetime.fromtimestamp(candle_ts/1000000).strftime('%Y-%m-%d %H:%M:%S')
print("OK")
im trying to convert timestamp to a readable format like so:
candle_ts = a_json['ticker']['lastQuote']['t'] #get the timestamp
print(candle_ts/1000000)
candle_ts = datetime.fromtimestamp(candle_ts/1000000).strftime('%Y-%m-%d %H:%M:%S')
the print is : 1644529277457.4104
I have no clue why but the error is :
candle_ts = datetime.fromtimestamp(candle_ts/1000000).strftime('%Y-%m-%d %H:%M:%S')
OSError: [Errno 22] Invalid argument
Why do I get such an unusual error??
The value for candle_ts is out of range, as you can see below sample script. The max limit is year 5138 which is around 11digits only. Your value for candle_ts is 13digits.
from datetime import datetime
candle_ts = 1644529277457.4104
try:
candle_ts = datetime.fromtimestamp(candle_ts).strftime('%Y-%m-%d %H:%M:%S')
print(candle_ts)
except Exception as e:
print(e)
Result:
year 54083 is out of range
I have a model in Django that has two DateFields, but sometimes they receive wrong dates from the front-end, like '20196-10-23'. Even when it might actually be a valid date (crazy, but legit), python doesn't allow to compare both dates due to this error: TypeError: '>=' not supported between instances of 'datetime.date' and 'str', so I want to use clean() method to verify that both dates are valid ones, but I always get dates wrong, even when they are correct.
This is the code for clean() method:
def clean(self, *args, **kwargs):
try:
Reservation.objects.get(booking=self.booking)
except:
pass
else:
raise CustomValidation(_('Booking already exists.'), 'booking', status_code=status.HTTP_400_BAD_REQUEST)
print("{}/{}".format(self.arrival_date, self.departure_date))
try:
datetime.strptime(self.arrival_date, "%Y-%m-%d")
except:
raise CustomValidation(_('Arrival date must be a valid date.'), 'arrival_date', status_code=status.HTTP_400_BAD_REQUEST)
if self.arrival_date >= self.departure_date:
raise CustomValidation(_('Departure date must be later than Arrival date.'), 'departure_date', status_code=status.HTTP_400_BAD_REQUEST)
elif self.arrival_date <= timezone.datetime.now().date():
if self.id == None:
raise CustomValidation(_('Arrival date must be later than today.'), 'arrival_date', status_code=status.HTTP_400_BAD_REQUEST)
if self.status == 'CONFIRMED' and self.confirmation is None:
raise CustomValidation(_('Must provide a confirmation number.'), 'confirmation', status_code=status.HTTP_400_BAD_REQUEST)
I always get an exception, even when the date is correct.
While 20196 is conceptually a valid year, Python won't allow it. I tried this...
import datetime
from datetime import date
def clean(arrival_date):
return date(*map(int, arrival_date.split("-")))
print(clean("20196-10-23"))
# ValueError: year is out of range
...and found out there's actually a hard-coded maximum year value of 9999 for Python dates.
So while you could technically validate the format in various ways, you won't be able to handle dates like this with the built-in datetime module.
I usually first set both dates as datetime.strptime():
try:
#get the dates
my_date_time_1 = self.cleaned_data['date_1']
my_date_time_2 = self.cleaned_data['date_2']
#set the datetime
my_date_time_1 = datetime.strptime(my_date_time_1, '%Y-%m-%d %H:%M:%S')
my_date_time_2 = datetime.strptime(my_date_time_2, '%Y-%m-%d %H:%M:%S')
except:
raise forms.ValidationError(u'Wrong Date Format')
#and then compare dates
if my_date_time_1 >= my_date_time_2:
raise forms.ValidationError(u'Please check the dates')
I am trying to create a number of constraints for some other code based on twitter handle sets.
I am having issues with the following code because:
TypeError: can't compare datetime.datetime to str
It seems that even though I have changed Last_Post to a datetime object initially, when i compare it to datetime.datetime.today() it is converting to string. Yes, I have checked the to ensure that Last_post is converting properly. Im not really sure what is going on. Help?
for handle in handles:
try:
user = api.get_user(handle)
#print json.dumps(user, indent = 4)
verified = user["verified"]
name = user['name']
language = user['lang']
follower_count = user['followers_count']
try:
last_post = user['status']['created_at']
last_post = datetime.strptime(last_post, '%a %b %d %H:%M:%S +0000 %Y')
except:
last_post = "User has not posted ever"
location = user['location']
location_ch = location_check(location)
if location_ch is not "United States":
location_output.append(False)
else:
location_output.append(True)
new_sum.append(follower_count)
if language is not "en":
lang_output.append(False)
else:
lang_output.append(True)
if datetime.datetime.today() - datetime.timedelta(days=30) > last_post:
recency.append(False)
else:
recency.append(True)
I think you need to convert the twitter date to a timestamp:
import time
ts = time.strftime('%Y-%m-%d %H:%M:%S', time.strptime(tweet['created_at'],'%a %b %d %H:%M:%S +0000 %Y'))
I'm currently coding an account signup on python and I need the user to enter their date of birth in the format DD/MM/YYYY.
How would I be able to check in the code if the input is valid or not?
dob=input("Enter your date of birth in the format DD/MM/YYYY")
import datetime
try:
date_of_birth = datetime.datetime.strptime(dob, "%d/%m/%Y")
except:
print("Incorrect date!")
Use following code
from datetime import datetime
i = str(raw_input('date'))
try:
dt_start = datetime.strptime(i, '%d/%m/%Y')
except ValueError:
print "Incorrect format"
Try using the datetime library
from datetime import datetime
def validate(date_text):
try:
datetime.datetime.strptime(date_text, '%d/%m/%Y')
except ValueError:
raise ValueError("Incorrect data format, should be YYYY-MM-DD")
I would like to parse a date that can come in several formats, that I know beforehand. If I could not parse, I return nil. In ruby, I do like this:
DATE_FORMATS = ['%m/%d/%Y %I:%M:%S %p', '%Y/%m/%d %H:%M:%S', '%d/%m/%Y %H:%M', '%m/%d/%Y', '%Y/%m/%d']
def parse_or_nil(date_str)
parsed_date = nil
DATE_FORMATS.each do |f|
parsed_date ||= DateTime.strptime(date_str, f) rescue nil
end
parsed_date
end
This is concise and works. How can I do the same thing in Python?
I would just try dateutil. It can recognize most of the formats:
from dateutil import parser
parser.parse(string)
if you end up using datetime.strptime as suggested #RocketDonkey:
from datetime import datetime
def func(s,flist):
for f in flist:
try:
return datetime.strptime(s,f)
except ValueError:
pass
You can use try/except to catch the ValueError that would occur when trying to use a non-matching format. As #Bakuriu mentions, you can stop the iteration when you find a match to avoid the unnecessary parsing, and then define your behavior when my_date doesn't get defined because not matching formats are found:
You can use try/except to catch the ValueError that would occur when trying to use a non-matching format:
from datetime import datetime
DATE_FORMATS = ['%m/%d/%Y %I:%M:%S %p', '%Y/%m/%d %H:%M:%S', '%d/%m/%Y %H:%M', '%m/%d/%Y', '%Y/%m/%d']
test_date = '2012/1/1 12:32:11'
for date_format in DATE_FORMATS:
try:
my_date = datetime.strptime(test_date, date_format)
except ValueError:
pass
else:
break
else:
my_date = None
print my_date # 2012-01-01 12:32:11
print type(my_date) # <type 'datetime.datetime'>
After your tip, RocketDonkey, and the one from Bakuriu, I could write a shorter version. Any problem with it?
def parse_or_none(date):
for date_format in DATE_FORMATS:
try:
return datetime.strptime(date, date_format)
except ValueError:
pass
return None
Modifying root's answer to handle m/d/y:
from dateutil import parser
parser.parse(string, dayfirst=False)
There's also a yearfirst option, to prefer y/m/d.