Posts

Showing posts with the label Datetime

Converting 13-digit Unixtime In Ms To Timestamp In Python

Answer : You have a millisecond-precise timestamp so first divide it by 1000 then feed it to datetime.datetime.fromtimestamp() for local timezone (or pass datetime.tzinfo of the target timezone as a second argument) or datetime.datetime.utcfromtimestamp() for UTC. Finally, use datetime.datetime.strftime() to turn it into a string of your desired format. import datetime timestamp = "1523126888080" your_dt = datetime.datetime.fromtimestamp(int(timestamp)/1000) # using the local timezone print(your_dt.strftime("%Y-%m-%d %H:%M:%S")) # 2018-04-07 20:48:08, YMMV

Convert Pandas Series To DateTime In A DataFrame

Answer : You can't: DataFrame columns are Series , by definition. That said, if you make the dtype (the type of all the elements) datetime-like, then you can access the quantities you want via the .dt accessor (docs): >>> df["TimeReviewed"] = pd.to_datetime(df["TimeReviewed"]) >>> df["TimeReviewed"] 205 76032930 2015-01-24 00:05:27.513000 232 76032930 2015-01-24 00:06:46.703000 233 76032930 2015-01-24 00:06:56.707000 413 76032930 2015-01-24 00:14:24.957000 565 76032930 2015-01-24 00:23:07.220000 Name: TimeReviewed, dtype: datetime64[ns] >>> df["TimeReviewed"].dt <pandas.tseries.common.DatetimeProperties object at 0xb10da60c> >>> df["TimeReviewed"].dt.year 205 76032930 2015 232 76032930 2015 233 76032930 2015 413 76032930 2015 565 76032930 2015 dtype: int64 >>> df["TimeReviewed"].dt.month 205 76032930 1 232 76032930 1 233 7...

Convert A Python UTC Datetime To A Local Datetime Using Only Python Standard Library?

Answer : In Python 3.3+: from datetime import datetime, timezone def utc_to_local(utc_dt): return utc_dt.replace(tzinfo=timezone.utc).astimezone(tz=None) In Python 2/3: import calendar from datetime import datetime, timedelta def utc_to_local(utc_dt): # get integer timestamp to avoid precision lost timestamp = calendar.timegm(utc_dt.timetuple()) local_dt = datetime.fromtimestamp(timestamp) assert utc_dt.resolution >= timedelta(microseconds=1) return local_dt.replace(microsecond=utc_dt.microsecond) Using pytz (both Python 2/3): import pytz local_tz = pytz.timezone('Europe/Moscow') # use your local timezone name here # NOTE: pytz.reference.LocalTimezone() would produce wrong result here ## You could use `tzlocal` module to get local timezone on Unix and Win32 # from tzlocal import get_localzone # $ pip install tzlocal # # get local timezone # local_tz = get_localzone() def utc_to_local(utc_dt): local_dt = utc_dt.replace(tzinfo=pytz.utc).astim...

Converting Between Datetime And Pandas Timestamp Objects

Answer : You can use the to_pydatetime method to be more explicit: In [11]: ts = pd.Timestamp('2014-01-23 00:00:00', tz=None) In [12]: ts.to_pydatetime() Out[12]: datetime.datetime(2014, 1, 23, 0, 0) It's also available on a DatetimeIndex: In [13]: rng = pd.date_range('1/10/2011', periods=3, freq='D') In [14]: rng.to_pydatetime() Out[14]: array([datetime.datetime(2011, 1, 10, 0, 0), datetime.datetime(2011, 1, 11, 0, 0), datetime.datetime(2011, 1, 12, 0, 0)], dtype=object) Pandas Timestamp to datetime.datetime: pd.Timestamp('2014-01-23 00:00:00', tz=None).to_pydatetime() datetime.datetime to Timestamp pd.Timestamp(datetime(2014, 1, 23)) >>> pd.Timestamp('2014-01-23 00:00:00', tz=None).to_datetime() datetime.datetime(2014, 1, 23, 0, 0) >>> pd.Timestamp(datetime.date(2014, 3, 26)) Timestamp('2014-03-26 00:00:00')

Add Default Value Of Datetime Field In SQL Server To A Timestamp

Image
Answer : For modifying an existing column in an existing table: ALTER TABLE YourTable ADD CONSTRAINT DF_YourTable DEFAULT GETDATE() FOR YourColumn This can also be done through the SSMS GUI. Put your table in design view (Right click on table in object explorer-> Design ) Add a column to the table (or click on the column you want to update if it already exists) In Column Properties, enter (getdate()) in Default Value or Binding field as pictured below In that table in SQL Server, specify the default value of that column to be CURRENT_TIMESTAMP . The datatype of that column may be datetime or datetime2 . e.g. Create Table Student ( Name varchar(50), DateOfAddmission datetime default CURRENT_TIMESTAMP );

Calculate Pandas DataFrame Time Difference Between Two Columns In Hours And Minutes

Answer : Pandas timestamp differences returns a datetime.timedelta object. This can easily be converted into hours by using the *as_type* method, like so import pandas df = pandas.DataFrame(columns=['to','fr','ans']) df.to = [pandas.Timestamp('2014-01-24 13:03:12.050000'), pandas.Timestamp('2014-01-27 11:57:18.240000'), pandas.Timestamp('2014-01-23 10:07:47.660000')] df.fr = [pandas.Timestamp('2014-01-26 23:41:21.870000'), pandas.Timestamp('2014-01-27 15:38:22.540000'), pandas.Timestamp('2014-01-23 18:50:41.420000')] (df.fr-df.to).astype('timedelta64[h]') to yield, 0 58 1 3 2 8 dtype: float64 This was driving me bonkers as the .astype() solution above didn't work for me. But I found another way. Haven't timed it or anything, but might work for others out there: t1 = pd.to_datetime('1/1/2015 01:00') t2 = pd.to_datetime('1/1/2015 03:30') print pd.Timedelta(t2...

Convert An RFC 3339 Time To A Standard Python Timestamp

Answer : You don't include an example, but if you don't have a Z-offset or timezone, and assuming you don't want durations but just the basic time, then maybe this will suit you: import datetime as dt >>> dt.datetime.strptime('1985-04-12T23:20:50.52', '%Y-%m-%dT%H:%M:%S.%f') datetime.datetime(1985, 4, 12, 23, 20, 50, 520000) The strptime() function was added to the datetime module in Python 2.5 so some people don't yet know it's there. Edit : The time.strptime() function has existed for a while though, and works about the same to give you a struct_time value: >>> ts = time.strptime('1985-04-12T23:20:50.52', '%Y-%m-%dT%H:%M:%S.%f') >>> ts time.struct_time(tm_year=1985, tm_mon=4, tm_mday=12, tm_hour=23, tm_min=20, tm_sec=50, tm_wday=4, tm_yday=102, tm_isdst=-1) >>> time.mktime(ts) 482210450.0 I struggled with RFC3339 datetime format a lot, but I found a suitable solution to convert date_string ...

Convert Date From Excel In Number Format To Date Format Python

Answer : from datetime import datetime excel_date = 42139 dt = datetime.fromordinal(datetime(1900, 1, 1).toordinal() + excel_date - 2) tt = dt.timetuple() print dt print tt As mentioned by J.F. Sebastian, this answer only works for any date after 1900/03/01 EDIT: (in answer to @R.K) If your excel_date is a float number, use this code: def floatHourToTime(fh): h, r = divmod(fh, 1) m, r = divmod(r*60, 1) return ( int(h), int(m), int(r*60), ) excel_date = 42139.23213 dt = datetime.fromordinal(datetime(1900, 1, 1).toordinal() + int(excel_date) - 2) hour, minute, second = floatHourToTime(excel_date % 1) dt = dt.replace(hour=hour, minute=minute, second=second) The module xlrd provides a function xldate_as_tuple to convert Excel's numerical date format to a tuple (year, month, day, hour, minute, nearest_second) . You can then use datetime.datetime to convert the tuple into a datetime -object. from datetime import datetime import xlrd excel_da...

Convert PHP Date Into Javascript Date Format

Answer : You should probably just use a timestamp $newticket['DateCreated'] = strtotime('now'); Then convert it to a Javascript date // make sure to convert from unix timestamp var now = new Date(dateFromPHP * 1000); Javascript Date class supports ISO 8601 date format so I would recommend: <?php date('c', $yourDateTime); // or for objects $dateTimeObject->format('c'); ?> documentation says that: format character 'c' is ISO 8601 date (added in PHP 5) example: 2004-02-12T15:19:21+00:00 for more information: http://php.net/manual/en/function.date.php It is pretty simple. PHP code: $formatted_date = $newticket['DateCreated'] = date('Y/m/d H:i:s'); Javascript code: var javascript_date = new Date("<?php echo $formatted_date; ?>");

Convert Datetime To Unix Timestamp And Convert It Back In Python

Answer : solution is import time import datetime d = datetime.date(2015,1,5) unixtime = time.mktime(d.timetuple()) What you missed here is timezones. Presumably you've five hours off UTC, so 2013-09-01T11:00:00 local and 2013-09-01T06:00:00Z are the same time. You need to read the top of the datetime docs, which explain about timezones and "naive" and "aware" objects. If your original naive datetime was UTC, the way to recover it is to use utcfromtimestamp instead of fromtimestamp . On the other hand, if your original naive datetime was local, you shouldn't have subtracted a UTC timestamp from it in the first place; use datetime.fromtimestamp(0) instead. Or, if you had an aware datetime object, you need to either use a local (aware) epoch on both sides, or explicitly convert to and from UTC. If you have, or can upgrade to, Python 3.3 or later, you can avoid all of these problems by just using the timestamp method instead of trying to figure out how to...

Convert Python Datetime To Epoch With Strftime

Answer : If you want to convert a python datetime to seconds since epoch you could do it explicitly: >>> (datetime.datetime(2012,04,01,0,0) - datetime.datetime(1970,1,1)).total_seconds() 1333238400.0 In Python 3.3+ you can use timestamp() instead: >>> datetime.datetime(2012,4,1,0,0).timestamp() 1333234800.0 Why you should not use datetime.strftime('%s') Python doesn't actually support %s as an argument to strftime (if you check at http://docs.python.org/library/datetime.html#strftime-and-strptime-behavior it's not in the list), the only reason it's working is because Python is passing the information to your system's strftime, which uses your local timezone. >>> datetime.datetime(2012,04,01,0,0).strftime('%s') '1333234800' I had serious issues with Timezones and such. The way Python handles all that happen to be pretty confusing (to me). Things seem to be working fine using the calendar module (see links 1, 2, 3 and...

Convert Python Datetime To Timestamp In Milliseconds

Answer : In Python 3 this can be done in 2 steps: Convert timestring to datetime object Multiply the timestamp of the datetime object by 1000 to convert it to milliseconds. For example like this: from datetime import datetime dt_obj = datetime.strptime('20.12.2016 09:38:42,76', '%d.%m.%Y %H:%M:%S,%f') millisec = dt_obj.timestamp() * 1000 print(millisec) Output: 1482223122760.0 strptime accepts your timestring and a format string as input. The timestring (first argument) specifies what you actually want to convert to a datetime object. The format string (second argument) specifies the actual format of the string that you have passed. Here is the explanation of the format specifiers from the official documentation: %d - Day of the month as a zero-padded decimal number. %m - Month as a zero-padded decimal number. %Y - Year with century as a decimal number %H - Hour (24-hour clock) as a zero-padded decimal number. %M - Minute as a ze...

Convert DateTime To String PHP

Answer : You can use the format method of the DateTime class: $date = new DateTime('2000-01-01'); $result = $date->format('Y-m-d H:i:s'); If format fails for some reason, it will return FALSE . In some applications, it might make sense to handle the failing case: if ($result) { echo $result; } else { // format failed echo "Unknown Time"; } The simplest way I found is: $date = new DateTime(); //this returns the current date time $result = $date->format('Y-m-d-H-i-s'); echo $result . "<br>"; $krr = explode('-', $result); $result = implode("", $krr); echo $result; I hope it helps. echo date_format($date,"Y/m/d H:i:s");

Converting Milliseconds To A Date (jQuery/JavaScript)

Answer : var time = new Date().getTime(); // get your number var date = new Date(time); // create Date object console.log(date.toString()); // result: Wed Jan 12 2011 12:42:46 GMT-0800 (PST) If you want custom formatting for your date I offer a simple function for it: var now = new Date; console.log( now.customFormat( "#DD#/#MM#/#YYYY# #hh#:#mm#:#ss#" ) ); Here are the tokens supported: token: description: example: #YYYY# 4-digit year 1999 #YY# 2-digit year 99 #MMMM# full month name February #MMM# 3-letter month name Feb #MM# 2-digit month number 02 #M# month number 2 #DDDD# full weekday name Wednesday #DDD# 3-letter weekday name Wed #DD# 2-digit day number 09 #D# day number 9 #th# day ordinal suffix nd #hhhh# 2-digit 24-based hour 17 #hhh# military/24-based hour 17 #hh# 2-digit hour ...

Calculating Difference Between Two Timestamps In Oracle In Milliseconds

Answer : When you subtract two variables of type TIMESTAMP , you get an INTERVAL DAY TO SECOND which includes a number of milliseconds and/or microseconds depending on the platform. If the database is running on Windows, systimestamp will generally have milliseconds. If the database is running on Unix, systimestamp will generally have microseconds. 1 select systimestamp - to_timestamp( '2012-07-23', 'yyyy-mm-dd' ) 2* from dual SQL> / SYSTIMESTAMP-TO_TIMESTAMP('2012-07-23','YYYY-MM-DD') --------------------------------------------------------------------------- +000000000 14:51:04.339000000 You can use the EXTRACT function to extract the individual elements of an INTERVAL DAY TO SECOND SQL> ed Wrote file afiedt.buf 1 select extract( day from diff ) days, 2 extract( hour from diff ) hours, 3 extract( minute from diff ) minutes, 4 extract( second from diff ) seconds 5 from (select systimes...