I'm taking input that looks like "8-15 14:45" and trying to turn it into a datetime object (and then turn it back into a string). My issue is that it sets the year to 1900, but I need the year set to this year. How do I accomplish this?
So far I have datetime.datetime.strptime('8-15 14:45', '%m-%d %H:%M') which gives me datetime.datetime(1900, 8, 15, 14, 45) but I need datetime.datetime(2021, 8, 15, 14, 45). I'd like to not hardcode 2021 if I can help it.
Apologies if this is answered somewhere, my google-fu has failed me.
Use datetime.replace with datetime.today().year:
this_year = dt.datetime.today().year
dt.datetime.strptime('8-15 14:45', '%m-%d %H:%M').replace(year=this_year)
You can use the method now() of the datetime class and only ask for the property year of the returned datetime object:
from datetime import datetime
t = datetime.now().year
print(t)
>>> 2021
You can do this by replacing the year on the parsed date like this:
from datetime import datetime as dt
date = dt.strptime('8-15 14:45', '%m-%d %H:%M')
date = date.replace(year=dt.now().year)
Related
I'm trying to convert strings in a list to datetime format on Python. I am unable to use pd.DateTime at the moment. The imported datetime package doesn't seem to work. I'm new to this.
Please help.
Cheers.
Code Image
You should consider using official datetime formats
Example:
from datetime import datetime
#datetime(year, month, day)
date = datetime(2018, 11, 28)
# datetime(year, month, day, hour, minute, second, microsecond)
date = datetime(2017, 11, 28, 23, 55, 59, 342380)
you can use strptime
from datetime import datetime, strptime
my_datetime_list = [strptime(string_date, '%y-%m-%d') for string_date in list_of_string_dates]
I have a date in this format - 2020-01-31T00:00:00.000Z, this is coming from an API. How do I get the month (e.g. April) and year (e.g. 2020) from this date using the datetime module?
I would suggest you to use the dateutil package to parse ISO 8601 dates.
>>> from dateutil import parser
>>> parser.isoparse('2020-01-31T00:00:00.000Z')
datetime.datetime(2020, 1, 31, 0, 0, tzinfo=tzutc())
Then you can retrieve the month and year from the datetime object it returns.
If you want to do using datetime module you can do this as
from datetime import datetime
input_dt = '2020-01-31T00:00:00.000Z'
dt_object = datetime.strptime(input_dt, "%Y-%m-%dT%H:%M:%S.%fz")
Now you can do
dt_object.year
dt_object.day
dt_object.month
The strptime() method creates a datetime object from the given string.
I have a date string and want to convert it to the date type:
I have tried to use datetime.datetime.strptime with the format that I want but it is returning the time with the conversion.
when = alldates[int(daypos[0])]
print when, type(when)
then = datetime.datetime.strptime(when, '%Y-%m-%d')
print then, type(then)
This is what the output returns:
2013-05-07 <type 'str'>
2013-05-07 00:00:00 <type 'datetime.datetime'>
I need to remove the time: 00:00:00.
print then.date()
What you want is a datetime.date object. What you have is a datetime.datetime object. You can either change the object when you print as per above, or do the following when creating the object:
then = datetime.datetime.strptime(when, '%Y-%m-%d').date()
If you need the result to be timezone-aware, you can use the replace() method of datetime objects. This preserves timezone, so you can do
>>> from django.utils import timezone
>>> now = timezone.now()
>>> now
datetime.datetime(2018, 8, 30, 14, 15, 43, 726252, tzinfo=<UTC>)
>>> now.replace(hour=0, minute=0, second=0, microsecond=0)
datetime.datetime(2018, 8, 30, 0, 0, tzinfo=<UTC>)
Note that this returns a new datetime object -- now remains unchanged.
>>> print then.date(), type(then.date())
2013-05-07 <type 'datetime.date'>
To convert a string into a date, the easiest way AFAIK is the dateutil module:
import dateutil.parser
datetime_object = dateutil.parser.parse("2013-05-07")
It can also handle time zones:
print(dateutil.parser.parse("2013-05-07"))
>>> datetime.datetime(2013, 5, 7, 1, 12, 12, tzinfo=tzutc())
If you have a datetime object, say:
import pytz
import datetime
now = datetime.datetime.now(pytz.UTC)
and you want chop off the time part, then I think it is easier to construct a new object instead of "substracting the time part". It is shorter and more bullet proof:
date_part datetime.datetime(now.year, now.month, now.day, tzinfo=now.tzinfo)
It also keeps the time zone information, it is easier to read and understand than a timedelta substraction, and you also have the option to give a different time zone in the same step (which makes sense, since you will have zero time part anyway).
For me, I needed to KEEP a timetime object because I was using UTC and it's a bit of a pain. So, this is what I ended up doing:
date = datetime.datetime.utcnow()
start_of_day = date - datetime.timedelta(
hours=date.hour,
minutes=date.minute,
seconds=date.second,
microseconds=date.microsecond
)
end_of_day = start_of_day + datetime.timedelta(
hours=23,
minutes=59,
seconds=59
)
Example output:
>>> date
datetime.datetime(2016, 10, 14, 17, 21, 5, 511600)
>>> start_of_day
datetime.datetime(2016, 10, 14, 0, 0)
>>> end_of_day
datetime.datetime(2016, 10, 14, 23, 59, 59)
If you specifically want a datetime and not a date but want the time zero'd out you could combine date with datetime.min.time()
Example:
datetime.datetime.combine(datetime.datetime.today().date(),
datetime.datetime.min.time())
You can use simply pd.to_datetime(then) and pandas will convert the date elements into ISO date format- [YYYY-MM-DD].
You can pass this as map/apply to use it in a dataframe/series too.
You can usee the following code:
week_start = str(datetime.today() - timedelta(days=datetime.today().weekday() % 7)).split(' ')[0]
I am working on a project , where I have dictionary with column date called "starttime" .. I need to extract month , hour and year , day of the week.
I am stuck for now I have the below code .
{if city =='NYC':
datn = datum[('starttime')]
datn = dt.strptime(datn,"%m/%d/%y %H:%M:%S")
hour = dt.strftime(datn,"%H")
year = dt.strftime(datn,"%y")
elif city == 'Chicago':
datc = datum[('starttime')]
datc = dt.strptime(datc,"%m/%d/%y %H:%M")
month = dt.strftime(datc,"%m")
hour = dt.strftime(datc,"%H")
year = dt.strftime(datc,"%y")
else:
datw = datum[('start date')]
datw = dt.strftime (datw,"%m")
hour = dt.strftime(datw,"%H")
year = dt.strftime(datw,"%y")
return (month, hour, day_of_week)
}
my import statements are on the top of my code , as below:
from datetime import datetime
strptime translates to
"parse (convert) string to datetime object."
strftime translates to
"create formatted string for given time/date/datetime object according to specified format."
Why do you need strftime?
This is what a datetime object looks like: (2015, 7, 19, 22, 7, 44,
377000)
To someone who isn't quite familiar with this format, with the
exception of the year, what's written up there is not immediately
intuitive. So you probably would be better off with something like
Sun, 19 July, 2015. That's what strftime is used for. You simply need
to learn the proper formatting strings.
One Good Link over SO read about this !
strptime converts the string to a datetime object.
strftime creates a formatted string for given time/date/datetime object according to specified format by the user
you would use strftime to convert a datetime object like this: datetime (2018, 10, 20, 10, 9, 22, 120401) to a more readable format like "20-10-2018" or 20th of October 2018.
I have dates in the form 26/11/2015. How can I convert them into the format 26-Nov-2015 and still keep them as dates and not strings?
Your question does not make much sense. If you keep them as dates, they have no format. The format is only manifested when you convert them to strings.
So the answer is: Store the dates as date (or datetime) objects, and use datetime.strftime with some specific format whenever you need them as a string:
>>> from datetime import date
>>> d = date(2016, 11, 26)
>>> d.strftime("%Y/%m/%d")
'2016/11/26'
>>> d.strftime("%d-%b-%Y")
'26-Nov-2016'
Conversely, use strptime to parse strings in different formats to dates:
>>> datetime.datetime.strptime("26-Nov-2015", "%d-%b-%Y")
datetime.datetime(2015, 11, 26, 0, 0)
from datetime import datetime
date = datetime.strptime('26/11/2015', '%d/%m/%Y')
print date.strftime("%d-%B-%Y")
In the above example, we are taking your input string 'dd/mm/yyyy' and turning it into a python datetime saving it to a variable called date (for future usage as per your request), and then printing it out in the format requested.
You want to use the datetime module I think. For example:
from datetime import date
a = date(2015, 11, 26)
a.strftime("%A %d of %B, %Y")
should give you 'Thursday 26 of November, 2015'
Or for your specific formatting request:
a.strftime("%d-%b-%Y") #'26-Nov-2015'
Hope this helps, good luck!