String to DateTime python - python

2020-03-04
I am extracting this from a file I read into a pandas Dataframe and want to transform it to datetime before I add a column and add the datetime to each row.
How can I transform this string to datetime?
Sorry for the newbie question, never dealt with this before.

Since you only have date value and it is in string form, you can use .strptime() methods of datetime.datetime.
This is how you can do it :
from datetime import datetime
myDate = "2020-03-04"
datetime.strptime(myDate, "%Y-%m-%d")
OutPut -> datetime.datetime(2020, 3, 4, 0, 0)

you can use this code:
import time
time=time.strftime('%m%d%H%M%Y.%S')
so the variable time contains the string content of the time.

Related

How to set a specific future datetime timestamp

I would LIKe to know how to set a specific DateTime timestamp using the DateTime module in python. For example if I want ... To happen on 1 August 2022. How can I make a DateTime timestamp that will hold that date. Thanks for all help in advance
You can construct a new datetime object with your date (and optionally with time) and then call timestamp() on it.
For example, you can do:
from datetime import datetime
timestamp = datetime(2022, 8, 1).timestamp()
# timestamp is now 1659304800.0
You can find the official documentation here.
To create a date, we can use the datetime() class (constructor) of the datetime module.
The datetime() class requires three parameters to create a date: year, month, day.
Example
Create a date object:
import datetime
x = datetime.datetime(2020, 5, 17)
print(x)
source

how to modify day which is inside a date string

i have seen some threats about this already but im not quite sure how to do mine. i have a string date (DD/MM/YY) then i need to subtract the day by 2 and i need to change it to (MM/DD/YY). For example, if i have a string of 01/04/2021, i need the final output to be 03/30/2021. i have tried using datetime.date but it seems like i cannot put a string of 01/04/2021 in it. Any helps? Here is what i got so far, but it doesn't really work i don't quite understand datetime library so its a little bit confusing, sorry in advance.
import datetime as dt
from dateutil.relativedelta import relativedelta
date_1 = '01/04/2021'
date_2 = list(date_1)
date_2[0:2], date_2[3:5] = date_2[3:5], date_2[0:2]
date_2 = ''.join(date_2) # change date_1 to MM/DD/YY
print(dt.date(int(date_2[0:4]),int(date_2[5:7]), int(date_2[8:10])) - relativedelta(days=2)) # i tried to minus the day out, but the code fails,
#Here is the error, in case it helps, ValueError: invalid literal for int() with base 10: '04/0'
You can use timedelta, strptime and strftime.
from datetime import datetime
from datetime import timedelta
d = '01/04/2021'
print((datetime.strptime(d, '%d/%m/%Y') - timedelta(days=2)).strftime('%m/%d/%y'))
#03/30/21
Explanation
datetime.strptime: This function allows you to take a string, provide the formatting and return a datetime object.
datetime.strptime(d, '%d/%m/%Y')
datetime.datetime(2021, 4, 1, 0, 0)
datetime.timedelta: Allows us to add and subtract time on a datetime object.
datetime.strptime(d, '%d/%m/%Y') - timedelta(days=2)
datetime.datetime(2021, 3, 30, 0, 0)
datetime.strftime: Allows us to format our datetime object as a string in the format we specify
datetime(2021, 3, 30, 0, 0).strftime('%m/%d/%y')
'03/30/21'
Joining these all together, we can convert your string to a date, make the change to the date that we want, and then convert it back to a string.

datetime.strptime formatting

My datetime in my CSV file is like the following:
2011/1/1 0:00
2011/1/1 0:30
2011/1/1 1:00
when I run:
date = datetime.strptime(row[0], '%Y/%m/%d %H:%M')
I get datetime output as:
[datetime.datetime(2011, 1, 1, 0, 0)]
[datetime.datetime(2011, 1, 1, 0, 30)]
How can i format it to the original datetime?
You have already parsed a string into a datetime object. This is done by using datetime.datetime.strptime(). To format the object back into a string you can use the same syntax but using method datetime.datetime.strftime(), e.g.:
date.strftime('%Y/%m/%d %H:%M')
See also documentation.
If you want exactly your input string (without leading 0), you can put a hyphen between percentage operator and directive character where necessary, e.g.:
date.strftime('%Y/%-m/%-d %-H:%M')
This is well explained in: Python strftime - date without leading 0 but it is platform dependent.
Try printing date in string format:
from datetime import datetime
row = "2011/1/1 0:30"
date = datetime.strptime(row, '%Y/%m/%d %H:%M')
print str(date)
output:
'2011-01-01 00:30:00'
What you are currently doing is creating a datetime object from a string and formatter as shown here. Likely somewhere in your code you put this object in a list and referenced it. Python doesn't know that you want to print the container(the list) with it in a certain string format.
If I'm understanding your question you want to print/return the element and not the container. Shown below:
import datetime
l = []
today = datetime.date.today()
l.append(today)
#what you have
print(l)
#addressing just the first element
print(l[0])

Convert string to NumPy datetime64 dtype

I program gets a string of current time every minute as date = '201711081750'
I want to store these strings as np.datetime64 into an array.
I think I could convert this kind of strings as
>>> date = '201711081750'
>>> np.datetime64( date[:4] +'-'+date[4:6]+'-'+date[6:8]+' ' +date[8:10]+':'+date[10:] , 'm' )
numpy.datetime64('2017-11-08T17:50')
But it looks complicated and I think it might engender errors later.
Are there simpler ways to do this?
pd.to_datetime
import pandas as pd
pd.to_datetime(date, format='%Y%m%d%H%M')
Timestamp('2017-11-08 17:50:00')
The important bit here is the format string '%Y%m%d%H%M'.
datetime.datetime equivalent in python.
from datetime import datetime as dt
dt.strptime(date, '%Y%m%d%H%M')
datetime.datetime(2017, 11, 8, 17, 50)

Python: convert 'days since 1990' to datetime object

I have a time series that I have pulled from a netCDF file and I'm trying to convert them to a datetime format. The format of the time series is in 'days since 1990-01-01 00:00:00 +10' (+10 being GMT: +10)
time = nc_data.variables['time'][:]
time_idx = 0 # first timestamp
print time[time_idx]
9465.0
My desired output is a datetime object like so (also GMT +10):
"2015-12-01 00:00:00"
I have tried converting this using the time module without much success although I believe I may be using wrong (I'm still a novice in python and programming).
import time
time_datetime = time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(time[time_idx]*24*60*60))
Any advice appreciated,
Cheers!
The datetime module's timedelta is probably what you're looking for.
For example:
from datetime import date, timedelta
days = 9465 # This may work for floats in general, but using integers
# is more precise (e.g. days = int(9465.0))
start = date(1990,1,1) # This is the "days since" part
delta = timedelta(days) # Create a time delta object from the number of days
offset = start + delta # Add the specified number of days to 1990
print(offset) # >>> 2015-12-01
print(type(offset)) # >>> <class 'datetime.date'>
You can then use and/or manipulate the offset object, or convert it to a string representation however you see fit.
You can use the same format as for this date object as you do for your time_datetime:
print(offset.strftime('%Y-%m-%d %H:%M:%S'))
Output:
2015-12-01 00:00:00
Instead of using a date object, you could use a datetime object instead if, for example, you were later going to add hours/minutes/seconds/timezone offsets to it.
The code would stay the same as above with the exception of two lines:
# Here, you're importing datetime instead of date
from datetime import datetime, timedelta
# Here, you're creating a datetime object instead of a date object
start = datetime(1990,1,1) # This is the "days since" part
Note: Although you don't state it, but the other answer suggests you might be looking for timezone aware datetimes. If that's the case, dateutil is the way to go in Python 2 as the other answer suggests. In Python 3, you'd want to use the datetime module's tzinfo.
netCDF num2date is the correct function to use here:
import netCDF4
ncfile = netCDF4.Dataset('./foo.nc', 'r')
time = ncfile.variables['time'] # do not cast to numpy array yet
time_convert = netCDF4.num2date(time[:], time.units, time.calendar)
This will convert number of days since 1900-01-01 (i.e. the units of time) to python datetime objects. If time does not have a calendar attribute, you'll need to specify the calendar, or use the default of standard.
We can do this in a couple steps. First, we are going to use the dateutil library to handle our work. It will make some of this easier.
The first step is to get a datetime object from your string (1990-01-01 00:00:00 +10). We'll do that with the following code:
from datetime import datetime
from dateutil.relativedelta import relativedelta
import dateutil.parser
days_since = '1990-01-01 00:00:00 +10'
days_since_dt = dateutil.parser.parse(days_since)
Now, our days_since_dt will look like this:
datetime.datetime(1990, 1, 1, 0, 0, tzinfo=tzoffset(None, 36000))
We'll use that in our next step, of determining the new date. We'll use relativedelta in dateutils to handle this math.
new_date = days_since_dt + relativedelta(days=9465.0)
This will result in your value in new_date having a value of:
datetime.datetime(2015, 12, 1, 0, 0, tzinfo=tzoffset(None, 36000))
This method ensures that the answer you receive continues to be in GMT+10.

Categories