How to set a specific future datetime timestamp - python

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

Related

python convert timestamp with timezone to datetime

dt = "2021-06-10T10:56:58.189+0200"
is my timestamp, which i want to convert into a datetime representation.
I use following code to do this:
d = dateutil.parser.parse(dt)
But my output looks like this:
2021-06-10 10:56:58.189000+02:00
Not much has changed. How can I include the information about the timezone in my newly created datetime object. I tried out a few more things from the documentation but can not work it out on my own..
Thanks in advance.
note that +0200 is a UTC offset, not a time zone ("America/Los_Angeles" is a time zone for example). If you wish to set a specific time zone, you can do it like
from datetime import datetime
from zoneinfo import ZoneInfo
# you can do the parsing with the standard lib:
s = "2021-06-10T10:56:58.189+0200"
dt = datetime.strptime(s, "%Y-%m-%dT%H:%M:%S.%f%z")
# now set a time zone:
dt_tz = dt.astimezone(ZoneInfo("Europe/Berlin"))
print(dt_tz) # __str__ gives you ISO format
# 2021-06-10 10:56:58.189000+02:00
print(dt_tz.strftime("%Y-%m-%dT%H:%M:%S %Z")) # custom format
# 2021-06-10T10:56:58 CEST
print(repr(dt_tz)) # object representation; __repr__
# datetime.datetime(2021, 6, 10, 10, 56, 58, 189000, tzinfo=zoneinfo.ZoneInfo(key='Europe/Berlin'))

Convert time (given in days since YYYY) into readable time format

I need help with converting time to a readable format. My time array (has 580 elements) is # of days since January 1st, 1900. How do I convert that to a normal time format (ie mm-dd-yyyy)?
For example, input time is 43,887 and output should read 02-27-2020 after adding it to Jan 1, 1900.
Thank you!
datetime.datetime and timedelta class can be helpful here.
from datetime import datetime, timedelta
def convert(inp, date1):
new_date = date1 + timedelta(inp)
return new_date.strftime("%m-%d-%Y")
date1 = datetime(1900, 1, 1)
print(convert(43887, date1))
You can use the datetime.datetime class can help you here. The following works, if those values are treated as integer days (you don't specify what they are).
from datetime import datetime
dt = datetime.fromordinal(43887)
dt.strftime('%d-%m-%Y')

String to DateTime 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.

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.

Python Date Utility Library

Is there a library in python that can produce date dimensions given a certain day? I'd like to use this for data analysis. Often I have a time series of dates, but for aggregation purposes I'd like to be able to quickly produce dates associated with that day - like first date of month, first day in week, and the like.
I think I could create my own, but if there is something out there already it'd be nice.
Thanks
Have a look at dateutil.
The recurrence rules and relative deltas are what you want.
For example, if you wanted to get last monday:
import dateutil.relativedelta as rd
import datetime
last_monday = datetime.date.today() + rd.relativedelta(weekday=rd.MO(-1))
time and datetime modules
For some of your purposes you can use time module with strftime() method or date module with its strftime() method. It allows you to pull, among other data:
number of the week of the year,
number of the weekday (you can also use weekday() method for getting weekday number between 0 for Monday and 6 for Sunday),
year,
month,
Which will suffice to calculate first day of the month, first day of the week and some other data.
Examples
To pull the data you need, do just:
to pull the number of the day of the week
>>> from datetime import datetime
>>> datetime.now().weekday()
6
to pull the first day of the month use replace() function of datetime object:
>>> from datetime import datetime
>>> datetime.now()
datetime.datetime(2012, 3, 3, 21, 41, 20, 953000)
>>> first_day_of_the_month = datetime.now().replace(day=1)
>>> first_day_of_the_month
datetime.datetime(2012, 3, 1, 21, 41, 20, 953000)
EDIT: As J.F. Sebastian suggested within comments, datetime objects have weekday() methods, which makes using int(given_date.strftime('%w')) rather pointless. I have updated the answer above.

Categories