can you tell me why it doesn't translate the date into numbers?
import datetime
from datetime import datetime
from datetime import timedelta
from django.db import models
def end_date():
return datetime.date.today() + timedelta(days=7)
def convert_date_str(add_date):
return datetime.strftime(add_date, "%m/%m/%Y")
class add(models.Model):
add_date = models.DateField('Дата додавання', auto_now_add=True)
end_date = models.DateField('Дата здачі', default=end_date)
as I do not output from the DB string month
First of all, strftime needs to be called on a datetime object so you need to enclose your addition statement in brackets.
from datetime import datetime, timedelta
def end_date():
return (datetime.today() + timedelta(days=7)).strftime("%d %B, %Y")
strptime is under datetime.datetime so you are going too deep. In any case, your second function doesn't make sense. You can only strptime from a string, not a datetime object. You also shouldn't use the same function and variable names. If you are trying to translate a datestring like 31/01/1999 to a datetime object, you can do
def convert_to_datetime(date_str):
return datetime.strptime(date_str, '%d/%m/%Y')
Your function names should also be more descriptive because at the moment I don't think any of them describes its actual functionality.
You're probably getting an Attribute error because timedelta has no strftime method. what you want is:
def end_date():
# add date object to timedelta first then get string
return (datetime.date.today() + timedelta(days=7)).strftime("%d %B, %Y")
second, strptime method takes a string and makes a datetime object. add_date is a date object not a string
def add_date():
add_date = datetime.date.today() # <-- this should be a string for strptime to work
# whats dt in your example?, also strptime argument must be a string
data_object = datetime.datetime.strptime(add_date, "%d %B, %Y").date()
return data_object
Related
Consider this:
from datetime import datetime
now = datetime.now()
now.strftime("%p") # returns 'PM'
'{0.day}'.format(now) # returns 22
'{0.strftime("%p")}'.format(now)
# gives
# AttributeError: 'datetime.datetime' object has no attribute 'strftime("%p")'
This seems to imply that I can't call a class method inside the format (I guess that's what strftime is).
What's a workaround for this (assuming I need to call the method inside the string, and keep using a format) ?
You could do this.
>>> from datetime import datetime
>>> now = datetime.now()
>>> '{0:%p}'.format(now)
'PM'
This will also work with f-strings.
>>> f"{now:%p}"
'PM'
You can use the f-string:
from datetime import datetime
now = datetime.now()
now.strftime("%p") # returns 'PM'
'{0.day}'.format(now) # returns 22
print(f'{now.strftime("%p")}')
Else:
from datetime import datetime
now = datetime.now()
now.strftime("%p") # returns 'PM'
'{0.day}'.format(now) # returns 22
print('{0:%p}'.format(now))
Documentation
strftime() and strptime() Behavior
You could use f-strings like this:
from datetime import datetime
now = datetime.now()
now.strftime("%p")
print(f'{now.day}')
print(f'{now.strftime("%p")}')
In python, I have a datetime object in python with that format.
datetime_object = datetime.strptime(date_time_str, '%Y-%m-%d %H:%M:%S')
In other classes, I'm using this object. When i reach this object,i want to extract time from it and compare string time.
Like below;
if "01:15:13" == time_from_datetime_object
How can I do this?
You need to use the strftime method:
from datetime import datetime
date_time_str = '2021-01-15 01:15:13'
datetime_object = datetime.strptime(date_time_str, '%Y-%m-%d %H:%M:%S')
if "01:15:13" == datetime_object.strftime('%H:%M:%S'):
print("match")
If you want to compare it as string:
if "01:15:13" == datetime_object.strftime('%H:%M:%S'):
Use its time method to return a time object, which you can compare to another time object.
from datetime import time
if datetime_object.time() == time(1, 15, 13):
...
You may have to be careful with microseconds though, so at some point you might want to do datetime_object = datetime_object.replace(microsecond=0), should your datetime objects contain non-zero microseconds.
I am very new to Python coding. I was trying to get the start and end date of a month and then compare it with another date column in the same excel.
I only need the date in mm/dd/yy format but do not need the time.
The final_month_end_date is basically a string format which I compare with an actual date but it gives me an error saying
"TypeError: Cannot compare type 'Timestamp' with type 'str'"
I have also tried .timestamp() function but of no use.
How can I resolve this problem?
import datetime as dt
import strftime
now1 = dt.datetime.now()
current_month= now1.month
current_year= now1.year
month_start_date= dt.datetime.today().strftime("%Y/%m/01")
month_end_date= calendar.monthrange(current_year,current_month)[1]
final_month_end_date= dt.datetime.today().strftime("%Y/%m/"+month_end_date)
To convert a string to a DateTime object use datetime.strptime. Once you have the datetime object, convert it to a unix timestamp using time.mktime.
import time
import datetime as dt
from time import mktime
from datetime import datetime
now1 = dt.datetime.now()
current_month= now1.month
current_year= now1.year
month_start_date= dt.datetime.today().strftime("%Y/%m/01")
month_end_date= "30"
final_month_end_date= dt.datetime.today().strftime("%Y/%m/"+month_end_date)
# Use datetime.strptime to convert from string to datetime
month_start = datetime.strptime(month_start_date, "%Y/%m/%d")
month_end = datetime.strptime(final_month_end_date, "%Y/%m/%d")
# Use time.mktime to convert datetime to timestamp
timestamp_start = time.mktime(month_start.timetuple())
timestamp_end = time.mktime(month_end.timetuple())
# Let's print the time stamps
print "Start timestamp: {0}".format(timestamp_start)
print "End timestamp: {0}".format(timestamp_end)
I am currently trying to convert a date in the following format YYYYmmddHHMMSS to a unix timestamp but I get an error (ValueError: year is out of range).
import datetime
def ts(date):
return datetime.datetime.fromtimestamp(date).strftime('%Y%m%d%H%M%S')
if __name__ == "__main__":
date = 20130814100000
print ts(date)
Your date should be a string. Here is how you do it. (If your date is an integer then just do date = str(date).
>>> import time
>>> from datetime import datetime
>>> date = '20130814100000'
>>> dt = datetime.strptime(date, '%Y%m%d%H%M%S')
>>> print dt
2013-08-14 10:00:00
>>> print time.mktime(dt.timetuple())
1376467200.0
time also has a strptime function but it returns a not so useful struct_time object. But if you only need a unix time, then you can use it too:
>>> time.mktime(time.strptime(date, '%Y%m%d%H%M%S'))
1376467200.0
I think the problem here is that .fromtimestamp() is expecting a Unix timestamp, not a date formatted as YYYYmmdd...
To parse the date information that you do have there, I'd recommend using .strptime() or the excellent python-dateutil package.
import datetime
def ts(date):
stamp = datetime.datetime.strptime(date, '%Y%m%d%H%M%S')
return stamp.strftime('%Y%m%d%H%M%S')
or
from dateutil.parser import parse
def ts(date):
stamp = parse(date)
return stamp.strftime('%Y%m%d%H%M%S')
http://labix.org/python-dateutil
The function that parses datetime is called strptime, not strftime (which formats time).
20130814100000 is not an UNIX timestamp
strptime takes string as argument
Overall, your code should look like:
import datetime
def ts(date):
return datetime.datetime.strptime(date, '%Y%m%d%H%M%S')
if __name__ == "__main__":
date = "20130814100000"
print ts(date)
You seem to have some confusion over the different ways that times are represented. The value you have assigned to date appears to already be a formatted timestring of "2013-08-14 10:00:00", but you're passing it into fromtimestamp. This function expects a Unix timestamp, which is simply the number of seconds that have elapsed since Midnight on Jan 1st 1970.
I believe something like this is what you're looking for:
import datetime
def ts(datestr):
return datetime.datetime.strptime(datestr, "%Y%m%d%H%M%S")
if __name__ == "__main__":
date = 20130814100000
print ts(date)
strftime like you had is for formatting times into strings. strptime is for parsing strings into times.
I am able to get the current time as below:
from datetime import datetime
str(datetime.now())[11:19]
Result
'19:43:20'
Now, I am trying to add 9 hours to the above time, how can I add hours to current time in Python?
from datetime import datetime, timedelta
nine_hours_from_now = datetime.now() + timedelta(hours=9)
#datetime.datetime(2012, 12, 3, 23, 24, 31, 774118)
And then use string formatting to get the relevant pieces:
>>> '{:%H:%M:%S}'.format(nine_hours_from_now)
'23:24:31'
If you're only formatting the datetime then you can use:
>>> format(nine_hours_from_now, '%H:%M:%S')
'23:24:31'
Or, as #eumiro has pointed out in comments - strftime
Import datetime and timedelta:
>>> from datetime import datetime, timedelta
>>> str(datetime.now() + timedelta(hours=9))[11:19]
'01:41:44'
But the better way is:
>>> (datetime.now() + timedelta(hours=9)).strftime('%H:%M:%S')
'01:42:05'
You can refer strptime and strftime behavior to better understand how python processes dates and time field
This works for me working with seconds not hours and also using a function to convert back to UTC time.
from datetime import timezone, datetime, timedelta
import datetime
def utc_converter(dt):
dt = datetime.datetime.now(timezone.utc)
utc_time = dt.replace(tzinfo=timezone.utc)
utc_timestamp = utc_time.timestamp()
return utc_timestamp
# create start and end timestamps
_now = datetime.datetime.now()
str_start = str(utc_converter(_now))
_end = _now + timedelta(seconds=10)
str_end = str(utc_converter(_end))
This is an answer which is significant for nowadays (python 3.9 or later).
Use strptime to create a datetime object from the timestring. Add 9 hours with timedelta, and match the time format with the timestring you have.
from datetime import datetime, timedelta
from zoneinfo import ZoneInfo
time_format = "%H:%M:%S"
timestring = datetime.strptime(str(datetime.now() + timedelta(hours=9))[11:19], time_format)
#You can then apply custom time formatting as well as a timezone.
TIMEZONE = [Add a timezone] #https://en.wikipedia.org/wiki/List_of_tz_database_time_zones
custom_time_format = "%H:%M"
time_modification = datetime.fromtimestamp(timestring.timestamp(), ZoneInfo(TIMEZONE)).__format__(custom_time_format)
While I think it's more meaningful to apply a timezone, you don't necessarily need to, so you can also simply do that:
time_format = "%H:%M:%S"
timestring = datetime.strptime(str(datetime.now() + timedelta(hours=9))[11:19], time_format)
time_modification = datetime.fromtimestamp(timestring.timestamp())
datetime
https://docs.python.org/3/library/datetime.html
strftime-and-strptime-format-codes
https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes
timedelta
https://docs.python.org/3/library/datetime.html#datetime.timedelta
zoneinfo
https://docs.python.org/3/library/zoneinfo.html#module-zoneinfo