How can I convert data into "ddmmyyyy hh:mm:ss"? - python

All that I have is the number 223 (which is the number of days from Jan 01,2012), and the time at which the event occurred at (for example: 09, 55, 56.38 = (hh, mm, ss)).
In Excel I can get a serial number - in the format 10-Aug-12 09:55:56 - with these four numbers.
In Python I've been having some troubles doing the same. Does anyone have any idea about what commands I could be using?

The timedelta class in Python's datetime module lets you create a time difference, in days (or other units), which you can add to/subtract from datetime objects to get a new date.
(Note: the datetime module contains a datetime object. Yup.)
So, you could construct a datetime object using 1st Jan 2012 and the hour, minute and second values you've got, and then add a timedelta of 223 days to it.
To get that datetime as a string in your desired format, the strftime method on the datetime object is your friend.
Putting it all on one line:
from datetime import datetime, timedelta
serial_number = (datetime(2012, 1, 1, 9, 55, 56) + timedelta(223)).strftime('%d-%h-%y %H:%M:%S')

Related

Add year/month/day to an UNIX timestamp with just hour/min/sec in python

The range of my timestamp is from 34200 to 57600, so it covers a part of one day from 9:30 AM). I want to add a specific year/month/day to this timestamp. How can I do that in python? Suppose that my timestamp is 34201.054427731004. I want a timestamp with information about year/month/day (for example, 3/2/2017) as the output. So here, the UNIX output is a full timestamp not just the hour/mean/sec.
Make a datetime object with the date, which will initialise hours and minutes to 0, and add a timedelta with the seconds to it:
from datetime import datetime, timedelta
date = datetime(2017, 2, 3) + timedelta(seconds=34201)
print(date.timestamp())

Python: Convertion of seconds from an initial date to datetime

I have measurements taken from 1st January 1993. They were recorded in second elapsed from that date. I would like to have them in date time.
I know in MatLab the function would be
time = datenum(1993,01,01,00,00, time)
However, I struggle to find an equivalent function in Python.
I have tried:
datetime.fromordinal(time) doesn't work because 'module object has no attribute fromordinal'?
datetime.datetime(time) doesn't work (I have a matrix because there are many scans done)
https://docs.python.org/3/library/datetime.html
You will first have to create a datetime object for Jan 1st 1993 and then add the number of seconds to that date. The code below should help you get started.
from datetime import datetime, timedelta
original_date = datetime.strptime('01-01-1993', '%d-%m-%Y')
original_date + timedelta(seconds= 10000)
output: datetime.datetime(1993, 1, 1, 2, 46, 40)
Let us say you have list of timevalues in seconds starting from 1993-01-01 00:00.
Easiest would be:
datevec=[datetime.datetime(1993,1,1,0)+datetime.timedelta(seconds=val) for val in timevector]
It is like UNIX time, but with a different start.
You can compute the offset once:
>>> import datetime as dt
>>> dt.datetime(1993,1,1).timestamp()
725842800.0
and use it in your program:
OFFSET = 725842800.0
mydate = dt.datetime.fromtimestamp(OFFSET + seconds_from_1993)

Subtract a year from given date (not current time) in python

I have a file in which date field in YYYYMMDD format. I need to pick that date and product to join with another file by subtracting 12 months to get other information.
File1
20180131,Apple
20180228,Orange
20180331,Grapes
File2
20170131,Apple,45
20170131,Orange,20
20170228,Orange,35
20170331,Apple,25
Output
20180131,Apple,45
20180228,Orange,35
20180331,Grapes,null
How to subtract 12 months or 1 year from given date(yyyymmdd) and get the answer in the same format.
You can use strptime from the standard library to parse the date, but unfortunately there is no calendar support in the standard library so you have to use the dateutil library to subtract the year.
import datetime
from dateutil.relativedelta import relativedelta
d = datetime.datetime.strptime('20180131', '%Y%m%d').date()
print((d - relativedelta(years=1)).strftime('%Y%m%d'))
This will print 20170131.
Note that if the input is e.g. 20160229, this will print out 20150228. I'm not sure exactly what the semantics of relativedelta are so be sure to read the docs if this is important to you.
Why not timedelta?
The datetime.timedelta is not appropriate and does not work correctly. A timedelta represents a duration in time, or it represents a number of days, but counter-intuitively, a year is not a duration but instead a calendrical concept. A year is either 365 or 366 days, depending on which year.
It becomes pretty obvious that timedelta will not work once you find the correct test cases:
In [1]: from datetime import date, timedelta
In [2]: date(2018, 1, 1) - timedelta(365)
Out[2]: datetime.date(2017, 1, 1)
In [3]: date(2017, 1, 1) - timedelta(365)
Out[3]: datetime.date(2016, 1, 2)

Parse and combine date and time (leap seconds) from strings - python

I parse a date (format: YYYY-MM-DD HH:MM:SS) from a data file which contains multiple lines of dates.
The problem is that the data contains leap seconds so i'm not able to use datetime. How can I take into account the leap seconds (0-60), so that at the end I would have the same result if I would have used datetime.strptime from the string with the format above (thus, date+time), please?
I have already tried with combine using date for the date and time for the time string. Is it the right way or are there some others?
Thanks in advance.
Just use time.strptime():
#!/usr/bin/env python
import datetime as DT
import time
from calendar import timegm
utc_time_string = '2012-06-30 23:59:60'
utc_time_tuple = time.strptime(utc_time_string, "%Y-%m-%d %H:%M:%S")[:6]
utc_dt = DT.datetime(1970, 1, 1) + DT.timedelta(seconds=timegm(utc_time_tuple))
# -> datetime.datetime(2012, 7, 1, 0, 0)
If the input time is not in UTC then you could handle the leap second in the time_tuple manually e.g., the datetime module may raise ValueError if you pass the leap second directly or it may silently truncate 60 to 59 if it encounters a leap second in indirect (internal) calls.

Check validity of datetime?

I would like to create a setter method for a datetime object so that I can customize the replace method. Is this possible?
For example:
datetime = datetime.replace(day = 34)
This throws an error because 34 is not a valid number of days for any month, but what I would like to do is increase the month by 1 and then subtract 28, 30, or 31 days.
You can subclass datetime and provide your own implementation of the replace method.
this doesn't answer your question directly, but if you're just trying to increment the datetime object, you can use timedelta. For example:
from datetime import datetime
from datetime import timedelta
datetime(2011, 1, 1) + timedelta(days=34)

Categories

Resources