convert date to number python [duplicate] - python

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Fetching datetime from float and vice versa in python
Like many people I switched from Matlab to Python. Matlab represents each date as a number. (Integers being days since 00-00-0000, and fractions being time in the day). I believe that python does the same except off a different start date 0-0-0001
I have been playing around with datetime, but cant seem to get away from datetime objects and timedeltas. I am sure this is dead simple, but how do I work with plain old numbers (floats)?
perhaps as a bit of context:
i bring in a date and time stamp and concatenate them to make one time value:
from datetime import datetime
date_object1 = datetime.strptime(date[1][0] + ' ' + date[1][1], '%Y-%m-%d %H:%M:%S')
date_object2 = datetime.strptime(date[2][0] + ' ' + date[2][1], '%Y-%m-%d %H:%M:%S')

Try this out:
import time
from datetime import datetime
t = datetime.now()
t1 = t.timetuple()
print time.mktime(t1)
It prints out a decimal representation of your date.

The datetime class provides two methods, datetime.timestamp() that gives you a float and datetime.fromtimestamp(timestamp) that does the reverse conversion. To get the timestamp corresponding to the current time you have the time.time() function.
Note that POSIX epoch is 1970-01-01.

Related

How to get time in '2022-12-01T09:13:45Z' this format? [duplicate]

This question already has answers here:
Python UTC datetime object's ISO format doesn't include Z (Zulu or Zero offset)
(13 answers)
Closed 3 months ago.
from datetime import datetime
import pytz
# local datetime to ISO Datetime
iso_date = datetime.now().replace(microsecond=0).isoformat()
print('ISO Datetime:', iso_date)
This doesn't give me the required format i want
2022-05-18T13:43:13
I wanted to get the time like '2022-12-01T09:13:45Z'
The time format that you want is known as Zulu time format, the following code changes UTC to Zulu format.
Example 1
import datetime
now = datetime.datetime.now(datetime.timezone.utc)
print(now)
Output
#2022-12-01 10:07:06.552326+00:00
Example 2 (Hack)
import datetime
now = datetime.datetime.now(datetime.timezone.utc)
now = now.strftime('%Y-%m-%dT%H:%M:%S')+ now.strftime('.%f')[:4] + 'Z'
print(now)
Output
#2022-12-01T10:06:41.122Z
Hope this helps. Happy Coding :)
You can use datime's strftime function i.e.
current_datetime = datetime.now().replace(microsecond=0)
print(f'ISO Datetime: {current_datetime.strftime("%Y-%m-%dT%H:%M:%SZ")}')

Python: How to convert a long datetime string to required format [duplicate]

This question already has answers here:
How do I parse an ISO 8601-formatted date?
(29 answers)
Closed 4 months ago.
I have this time here : 2017-08-05T05:21:10.6582942Z
And I want to convert it into %Y-%m-%d %H:%M:%S
I can do that using some funky methods such as :
date = "2017-08-05T05:21:10.6582942Z"
new_date = date[:11] + " " + date[12:][:-9]
But is there any way I can do something cleaner with datetime or some libraries made for this specific purpose ?
Using the datetime library with the strptime method (for parsing) and the strftime method (for formatting), this can be accomplished with no splits and limited slicing as:
from datetime import datetime as dt
date = '2017-08-05T05:21:10.6582942Z'
output = dt.strptime(date[:-2], '%Y-%m-%dT%H:%M:%S.%f').strftime('%Y-%m-%d %H:%M:%S')
Output:
'2017-08-05 05:21:10'
Note:
The slice is needed to remove the last two characters from the string date, as the %f (fractional seconds) formatter only accepts six decimal values, and your string contains seven decimal values.
Per the formatting documentation:
%f: Microsecond as a decimal number, zero-padded to 6 digits.
Start with importing datetime:
import datetime as dt
Convert string to datetime object:
date = "2017-08-05T05:21:10.6582942Z"
new_date = dt.datetime.strptime(date[:-2], "%Y-%m-%dT%H:%M:%S.%f") # -2 slice to since %f only accepts 6 digits.
Format datetime object as string:
format_date = dt.datetime.strftime(new_date, "%Y-%m-%d %H:%M:%S") # returns your format
However, looking at your code it feels your date is already formatted and you don't require the last .strftime() usage.

How to convert HH:MM:SS to time.time() object in Python [duplicate]

This question already has answers here:
Convert string "Jun 1 2005 1:33PM" into datetime
(26 answers)
Closed 2 years ago.
I need to convert HH:MM:SS format to time.time() object. Is there any way to do it?
Here's my HH:MM:SS format time:
a = '14:37:29'
I want to convert it to time.time() object such as:
a = 1600256249
Is this achievable? If it's not, what should I try? Hope you help.
To get UNIX time, you need to add a date. For example, you could combine your time string with today's date:
from datetime import datetime, timezone
s = '14:37:29'
today = datetime.today() # 2020-09-16
# make a datetime object with today's date
dt = datetime.combine(today, datetime.strptime(s, '%H:%M:%S').time())
# make sure it's in UTC (optional)
dt = dt.replace(tzinfo=timezone.utc)
# get the timestamp
ts = dt.timestamp()
print(ts)
# 1600267049.0
You could also set other time zones with this approach using dateutil or zoneinfo (Python 3.9+).
Is this achievable?
I would say no. a = '14:37:29' holds only hour-minute-second, whilst time.time() does return seconds since start of epoch i.e. you would also need to known day, month and year beside hour, minute, second, to create equivalent of what time.time() returns.

how to create a date object in python representing a set number of days

I would like to define a variable to be a datetime object representing the number of days that is entered by the user. For example.
numDays = #input from user
deltaDatetime = #this is what I'm trying to figure out how to do
str(datetime.datetime.now() + deltaDatetime)
This code would print out a datetime representing 3 days from today if the user entered 3 as their input. Any idea how to do this? I'm completely lost as to an effective approach to this problem.
EDIT: Because of how my system is set up, the variable storing the "deltaDatetime" value must be a datetime value. As I said in the comments, something like 3 days becomes Year 0, January 3rd.
It's fairly straightforward using timedelta from the standard datetime library:
import datetime
numDays = 5 # heh, removed the 'var' in front of this (braincramp)
print datetime.datetime.now() + datetime.timedelta(days=numDays)
deltaDateTime = datetime.timedelta(days=3)
Use timedelta:
from datetime import datetime, timedelta
days = int(raw_input())
print datetime.now() + timedelta(days=days)

How to convert integer into date object python?

I am creating a module in python, in which I am receiving the date in integer format like 20120213, which signifies the 13th of Feb, 2012. Now, I want to convert this integer formatted date into a python date object.
Also, if there is any means by which I can subtract/add the number of days in such integer formatted date to receive the date value in same format? like subtracting 30 days from 20120213 and receive answer as 20120114?
This question is already answered, but for the benefit of others looking at this question I'd like to add the following suggestion: Instead of doing the slicing yourself as suggested in the accepted answer, you might also use strptime() which is (IMHO) easier to read and perhaps the preferred way to do this conversion.
import datetime
s = "20120213"
s_datetime = datetime.datetime.strptime(s, '%Y%m%d')
I would suggest the following simple approach for conversion:
from datetime import datetime, timedelta
s = "20120213"
# you could also import date instead of datetime and use that.
date = datetime(year=int(s[0:4]), month=int(s[4:6]), day=int(s[6:8]))
For adding/subtracting an arbitary amount of days (seconds work too btw.), you could do the following:
date += timedelta(days=10)
date -= timedelta(days=5)
And convert back using:
s = date.strftime("%Y%m%d")
To convert the integer to a string safely, use:
s = "{0:-08d}".format(i)
This ensures that your string is eight charecters long and left-padded with zeroes, even if the year is smaller than 1000 (negative years could become funny though).
Further reference: datetime objects, timedelta objects
Here is what I believe answers the question (Python 3, with type hints):
from datetime import date
def int2date(argdate: int) -> date:
"""
If you have date as an integer, use this method to obtain a datetime.date object.
Parameters
----------
argdate : int
Date as a regular integer value (example: 20160618)
Returns
-------
dateandtime.date
A date object which corresponds to the given value `argdate`.
"""
year = int(argdate / 10000)
month = int((argdate % 10000) / 100)
day = int(argdate % 100)
return date(year, month, day)
print(int2date(20160618))
The code above produces the expected 2016-06-18.
import datetime
timestamp = datetime.datetime.fromtimestamp(1500000000)
print(timestamp.strftime('%Y-%m-%d %H:%M:%S'))
This will give the output:
2017-07-14 08:10:00

Categories

Resources