I am trying to convert a time string into a datetime object where the date is today's date. However, I only have a time string and its replace() method does not seem to work.
from datetime import datetime, time,date
timestr = "9:30"
startTime = datetime.strptime(timestr,"%H:%M")
startTime.replace(year=datetime.now().year, month=datetime.now().month, day=datetime.now().day)
print startTime
>>> 1900-01-01 09:30:00
I want:
2017-01-20 09:30:00
nicer than replace is combine:
timestr = "9:30"
startTime = datetime.strptime(timestr,"%H:%M")
d = datetime.combine(datetime.today(), startTime.time())
replace doesn't work in-place. Don't ignore the return value, assign it back like this:
startTime = startTime.replace(year=datetime.now().year, month=datetime.now().month, day=datetime.now().day)
and you get:
2017-01-20 09:30:00
Here is another solution using another library.
import pendulum
timestr = "9:30"
dt = pendulum.parse(timestr)
<Pendulum [2017-01-20T09:30:00+00:00]>
Or
dt = pendulum.parse(timestr).to_datetime_string()
'2017-01-20 09:30:00'
Related
I using:
s = "20200113"
final = datetime.datetime.strptime(s, '%Y%m%d')
I need convert a number in date format (2020-01-13)
but when I print final:
2020-01-13 00:00:00
Tried datetime.date(s, '%Y%m%d') but It's returns a error:
an integer is required (got type str)
Is there any command to get only date without hour?
Once you have a datetime object just use strftime
import datetime
d = datetime.datetime.now() # Some datetime object.
print(d.strftime('%Y-%m-%d'))
which gives
2020-02-20
You can use strftime to convert back in the format you need :
import datetime
s = "20200113"
temp = datetime.datetime.strptime(s, '%Y%m%d')
# 2020-01-13 00:00:00
final = temp.strftime('%Y-%m-%d')
print(final)
# 2020-01-13
Use datetime.date(year, month, day). Slice your string and convert to integers to get the year, month and day. Now it is a datetime.date object, you can use it for other things. Here, however, we use .strftime to convert it back to text in your desired format.
s = "20200113"
year = int(s[:4]) # 2020
month = int(s[4:6]) # 1
day = int(s[6:8]) # 13
>>> datetime.date(year, month, day).strftime('%Y-%m-%d')
'2020-01-13'
You can also convert directly via strings.
>>> f'{s[:4]}-{s[4:6]}-{s[6:8]}'
'2020-01-13'
You can use .date() on datetime objects to 'remove' the time.
my_time_str = str(final.date())
will give you the wanted result
I'm trying to subtract a day from this date 06-30-2019 in order to make it 06-29-2019 but can't figure out any way to achive that.
I've tried with:
import datetime
date = "06-30-2019"
date = datetime.datetime.strptime(date,'%m-%d-%Y').strftime('%m-%d-%Y')
print(date)
It surely gives me back the date I used above.
How can I subtract a day from a date in the above format?
try this
import datetime
date = "06/30/19"
date = datetime.datetime.strptime(date, "%m/%d/%y")
NewDate = date + datetime.timedelta(days=-1)
print(NewDate) # 2019-06-29 00:00:00
Your code:
date = "06-30-2019"
date = datetime.datetime.strptime(date,'%m-%d-%Y').strftime('%m-%d-%Y')
Check type of date variable.
type(date)
Out[]: str
It is in string format. To perform subtraction operation you must convert it into date format first. You can use pd.to_datetime()
# Import packages
import pandas as pd
from datetime import timedelta
# input date
date = "06-30-2019"
# Convert it into pd.to_datetime format
date = pd.to_datetime(date)
print(date)
# Substracting days
number_of_days = 1
new_date = date - timedelta(number_of_days)
print(new_date)
output:
2019-06-29 00:00:00
If you want to get rid of timestamp you can use:
str(new_date.date())
Out[]: '2019-06-29'
use timedelta
import datetime
date = datetime.datetime.strptime("06/30/19" ,"%m/%d/%y")
print( date - datetime.timedelta(days=1))
Basically I have an entire dataframe with the timestamp in the following format:
2018-01-17T05:00:00.000000Z
And I'm looking to add different seconds on it (sometimes add 1 second, sometimes add 1 microsecond, etc).
The python datetime allows you to use milliseconds and microseconds.
>>> from datetime import datetime,timedelta
>>> dt = datetime.now()
>>> print(dt)
2019-07-05 17:21:49.523664
>>> dt1 = dt + timedelta(microseconds = 1,milliseconds = 1)
>>> print(dt1)
2019-07-05 17:21:49.524665
Regarding the nanoseconds you can find information here.
In case you have it as a string you have to transform it into datetime:
>>> from datetime import datetime,timedelta
>>> import dateutil.parser
>>> date = dateutil.parser.parse("2018-01-17T05:00:00.000000Z")
>>> print(date)
2018-01-17 05:00:00+00:00
>>> dt1 = date + timedelta(microseconds = 1,milliseconds = 1)
>>> print(dt1)
2018-01-17 05:00:00.001001+00:00
If you ask for the last part of the date +00:00, it is for the time zone you can remove it like this:
>>> dt1 = dt1.replace(tzinfo=None)
>>> print(dt1)
2018-01-17 05:00:00.001001
With Python 3.7 you may use datetime.fromisoformat:
import datetime
value = datetime.datetime.fromisoformat(str)
value += datetime.timedelta(seconds=1)
With older Python version you may use:
import datetime
value = datetime.datetime.strptime(str, "%Y-%m-%dT%H:%M:%S.%fZ")
value += datetime.timedelta(seconds=1)
I have a slice function in Python that slices parse dates like "1960-01-01". I have tried to assign variables to make the code generic, However, when the data is not called like this :
calibration_period = slice('1960-01-01', '2000-12-31')
validation_period = slice('2001-01-01', '2014-12-31')
and called like:
calibration_period = slice(Base, Date[-1])
validation_period = slice(Date2[0],Date2[-1])
The last value is read as 2014-12-31 00:00:00, but I want to read it as "2014-12-31" so the calculations continue up to 2014-12-31 23:00:00.
I have used this:
from datetime import datetime
t=pd.to_datetime(str(Date2[-1]))
strg=t.strftime('%Y-%m-%d')
although the print function shows it as 2014-12-31 the print for validation is still:
slice(numpy.datetime64('2001-01-01T00:00:00.000000000'), Timestamp('2014-12-31 00:00:00'), None)
I would be really grateful if someone has a suggestion.
I think the issue is you're mixing up datetime formats and string formats.
from datetime import datetime
time = datetime.strptime('01/01/2010', '%d/%m/%Y')
newtime = datetime.strftime(time, '%d/%m/%Y')
print(time, newtime)
2010-01-01 00:00:00 01/01/2010
Press any key to continue . . .
Convert your date times to a string with the format you want using datetime.strftime, then you can use logic to do the calculation, i.e:
A datetime object with value 2010-01-01 23:30:00 will always be converted to a string of type 2010-01-01 when using:
value = datetime.strftime(value, '%Y-%m-%d')
Can then perform logic on the two strings
if value == newtime:
print(value)
Full example:
from datetime import datetime
time = datetime.strptime('01/01/2010 20:30:30', '%d/%m/%Y %H:%M:%S')
newtime = datetime.strftime(time, '%d/%m/%Y')
print(time)
print(newtime)
#Outputs:
2010-01-01 20:30:30
01/01/2010
May be helpful
>>> from datetime import datetime
>>> d = datetime.utcnow()
>>> d.date()
datetime.date(2018, 7, 10)
>>> str(d.date())
'2018-07-10'
I have:
test_date = "2017-07-20-10-30"
and then use:
day = datetime.strptime(test_date[11:], "%H-%M")
which gives me
1900-01-01 10:30:00
How do I just get: 10:30:00 as type datetime.time?
You can use the strftime method of the datetime object like this:
day.strftime('%H:%M')
More information here: https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior
Ok, I misunderstood. Use day.time() to get a time object.
you can parse your string using datetime.strptime to a datetime object and then call .time() on that to get the time:
from datetime import datetime
strg = "2017-07-20-10-30"
dt = datetime.strptime(strg, '%Y-%m-%d-%H-%M')
tme = dt.time()
print(tme) # 10:30:00
the strftime() and strptime() Behavior is well documented.
of course you can also chain these calls:
tme = datetime.strptime(strg, '%Y-%m-%d-%H-%M').time()